

var FLD_JS = "/scripts/js/"; 

/**
 *
 * Color picker
 * Author: Stefan Petre www.eyecon.ro
 * 
 * Dual licensed under the MIT and GPL licenses
 * 
 */
(function ($) {
	var ColorPicker = function () {
		var
			ids = {},
			inAction,
			charMin = 65,
			visible,
			tpl = '<div class="colorpicker"><div class="colorpicker_color"><div><div></div></div></div><div class="colorpicker_hue"><div></div></div><div class="colorpicker_new_color"></div><div class="colorpicker_current_color"></div><div class="colorpicker_hex"><input type="text" maxlength="6" size="6" /></div><div class="colorpicker_rgb_r colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_g colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_rgb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_h colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_s colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_hsb_b colorpicker_field"><input type="text" maxlength="3" size="3" /><span></span></div><div class="colorpicker_submit"></div></div>',
			defaults = {
				eventName: 'click',
				onShow: function () {},
				onBeforeShow: function(){},
				onHide: function () {},
				onChange: function () {},
				onSubmit: function () {},
				color: 'ff0000',
				livePreview: true,
				flat: false
			},
			fillRGBFields = function  (hsb, cal) {
				var rgb = HSBToRGB(hsb);
				$(cal).data('colorpicker').fields
					.eq(1).val(rgb.r).end()
					.eq(2).val(rgb.g).end()
					.eq(3).val(rgb.b).end();
			},
			fillHSBFields = function  (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(4).val(hsb.h).end()
					.eq(5).val(hsb.s).end()
					.eq(6).val(hsb.b).end();
			},
			fillHexFields = function (hsb, cal) {
				$(cal).data('colorpicker').fields
					.eq(0).val(HSBToHex(hsb)).end();
			},
			setSelector = function (hsb, cal) {
				$(cal).data('colorpicker').selector.css('backgroundColor', '#' + HSBToHex({h: hsb.h, s: 100, b: 100}));
				$(cal).data('colorpicker').selectorIndic.css({
					left: parseInt(150 * hsb.s/100, 10),
					top: parseInt(150 * (100-hsb.b)/100, 10)
				});
			},
			setHue = function (hsb, cal) {
				$(cal).data('colorpicker').hue.css('top', parseInt(150 - 150 * hsb.h/360, 10));
			},
			setCurrentColor = function (hsb, cal) {
				$(cal).data('colorpicker').currentColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			setNewColor = function (hsb, cal) {
				$(cal).data('colorpicker').newColor.css('backgroundColor', '#' + HSBToHex(hsb));
			},
			keyDown = function (ev) {
				var pressedKey = ev.charCode || ev.keyCode || -1;
				if ((pressedKey > charMin && pressedKey <= 90) || pressedKey == 32) {
					return false;
				}
				var cal = $(this).parent().parent();
				if (cal.data('colorpicker').livePreview === true) {
					change.apply(this);
				}
			},
			change = function (ev) {
				var cal = $(this).parent().parent(), col;
				if (this.parentNode.className.indexOf('_hex') > 0) {
					cal.data('colorpicker').color = col = HexToHSB(fixHex(this.value));
				} else if (this.parentNode.className.indexOf('_hsb') > 0) {
					cal.data('colorpicker').color = col = fixHSB({
						h: parseInt(cal.data('colorpicker').fields.eq(4).val(), 10),
						s: parseInt(cal.data('colorpicker').fields.eq(5).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(6).val(), 10)
					});
				} else {
					cal.data('colorpicker').color = col = RGBToHSB(fixRGB({
						r: parseInt(cal.data('colorpicker').fields.eq(1).val(), 10),
						g: parseInt(cal.data('colorpicker').fields.eq(2).val(), 10),
						b: parseInt(cal.data('colorpicker').fields.eq(3).val(), 10)
					}));
				}
				if (ev) {
					fillRGBFields(col, cal.get(0));
					fillHexFields(col, cal.get(0));
					fillHSBFields(col, cal.get(0));
				}
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
				cal.data('colorpicker').onChange.apply(cal, [col, HSBToHex(col), HSBToRGB(col)]);
			},
			blur = function (ev) {
				var cal = $(this).parent().parent();
				cal.data('colorpicker').fields.parent().removeClass('colorpicker_focus');
			},
			focus = function () {
				charMin = this.parentNode.className.indexOf('_hex') > 0 ? 70 : 65;
				$(this).parent().parent().data('colorpicker').fields.parent().removeClass('colorpicker_focus');
				$(this).parent().addClass('colorpicker_focus');
			},
			downIncrement = function (ev) {
				var field = $(this).parent().find('input').focus();
				var current = {
					el: $(this).parent().addClass('colorpicker_slider'),
					max: this.parentNode.className.indexOf('_hsb_h') > 0 ? 360 : (this.parentNode.className.indexOf('_hsb') > 0 ? 100 : 255),
					y: ev.pageY,
					field: field,
					val: parseInt(field.val(), 10),
					preview: $(this).parent().parent().data('colorpicker').livePreview					
				};
				$(document).bind('mouseup', current, upIncrement);
				$(document).bind('mousemove', current, moveIncrement);
			},
			moveIncrement = function (ev) {
				ev.data.field.val(Math.max(0, Math.min(ev.data.max, parseInt(ev.data.val + ev.pageY - ev.data.y, 10))));
				if (ev.data.preview) {
					change.apply(ev.data.field.get(0), [true]);
				}
				return false;
			},
			upIncrement = function (ev) {
				change.apply(ev.data.field.get(0), [true]);
				ev.data.el.removeClass('colorpicker_slider').find('input').focus();
				$(document).unbind('mouseup', upIncrement);
				$(document).unbind('mousemove', moveIncrement);
				return false;
			},
			downHue = function (ev) {
				var current = {
					cal: $(this).parent(),
					y: $(this).offset().top
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upHue);
				$(document).bind('mousemove', current, moveHue);
			},
			moveHue = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(4)
						.val(parseInt(360*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.y))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upHue = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upHue);
				$(document).unbind('mousemove', moveHue);
				return false;
			},
			downSelector = function (ev) {
				var current = {
					cal: $(this).parent(),
					pos: $(this).offset()
				};
				current.preview = current.cal.data('colorpicker').livePreview;
				$(document).bind('mouseup', current, upSelector);
				$(document).bind('mousemove', current, moveSelector);
			},
			moveSelector = function (ev) {
				change.apply(
					ev.data.cal.data('colorpicker')
						.fields
						.eq(6)
						.val(parseInt(100*(150 - Math.max(0,Math.min(150,(ev.pageY - ev.data.pos.top))))/150, 10))
						.end()
						.eq(5)
						.val(parseInt(100*(Math.max(0,Math.min(150,(ev.pageX - ev.data.pos.left))))/150, 10))
						.get(0),
					[ev.data.preview]
				);
				return false;
			},
			upSelector = function (ev) {
				fillRGBFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				fillHexFields(ev.data.cal.data('colorpicker').color, ev.data.cal.get(0));
				$(document).unbind('mouseup', upSelector);
				$(document).unbind('mousemove', moveSelector);
				return false;
			},
			enterSubmit = function (ev) {
				$(this).addClass('colorpicker_focus');
			},
			leaveSubmit = function (ev) {
				$(this).removeClass('colorpicker_focus');
			},
			clickSubmit = function (ev) {
				var cal = $(this).parent();
				var col = cal.data('colorpicker').color;
				cal.data('colorpicker').origColor = col;
				setCurrentColor(col, cal.get(0));
				cal.data('colorpicker').onSubmit(col, HSBToHex(col), HSBToRGB(col), cal.data('colorpicker').el);
			},
			show = function (ev) {
				var cal = $('#' + $(this).data('colorpickerId'));
				cal.data('colorpicker').onBeforeShow.apply(this, [cal.get(0)]);
				var pos = $(this).offset();
				var viewPort = getViewport();
				var top = pos.top + this.offsetHeight;
				var left = pos.left;
				if (top + 176 > viewPort.t + viewPort.h) {
					top -= this.offsetHeight + 176;
				}
				if (left + 356 > viewPort.l + viewPort.w) {
					left -= 356;
				}
				cal.css({left: left + 'px', top: top + 'px'});
				if (cal.data('colorpicker').onShow.apply(this, [cal.get(0)]) != false) {
					cal.show();
				}
				$(document).bind('mousedown', {cal: cal}, hide);
				return false;
			},
			hide = function (ev) {
				if (!isChildOf(ev.data.cal.get(0), ev.target, ev.data.cal.get(0))) {
					if (ev.data.cal.data('colorpicker').onHide.apply(this, [ev.data.cal.get(0)]) != false) {
						ev.data.cal.hide();
					}
					$(document).unbind('mousedown', hide);
				}
			},
			isChildOf = function(parentEl, el, container) {
				if (parentEl == el) {
					return true;
				}
				if (parentEl.contains) {
					return parentEl.contains(el);
				}
				if ( parentEl.compareDocumentPosition ) {
					return !!(parentEl.compareDocumentPosition(el) & 16);
				}
				var prEl = el.parentNode;
				while(prEl && prEl != container) {
					if (prEl == parentEl)
						return true;
					prEl = prEl.parentNode;
				}
				return false;
			},
			getViewport = function () {
				var m = document.compatMode == 'CSS1Compat';
				return {
					l : window.pageXOffset || (m ? document.documentElement.scrollLeft : document.body.scrollLeft),
					t : window.pageYOffset || (m ? document.documentElement.scrollTop : document.body.scrollTop),
					w : window.innerWidth || (m ? document.documentElement.clientWidth : document.body.clientWidth),
					h : window.innerHeight || (m ? document.documentElement.clientHeight : document.body.clientHeight)
				};
			},
			fixHSB = function (hsb) {
				return {
					h: Math.min(360, Math.max(0, hsb.h)),
					s: Math.min(100, Math.max(0, hsb.s)),
					b: Math.min(100, Math.max(0, hsb.b))
				};
			}, 
			fixRGB = function (rgb) {
				return {
					r: Math.min(255, Math.max(0, rgb.r)),
					g: Math.min(255, Math.max(0, rgb.g)),
					b: Math.min(255, Math.max(0, rgb.b))
				};
			},
			fixHex = function (hex) {
				var len = 6 - hex.length;
				if (len > 0) {
					var o = [];
					for (var i=0; i<len; i++) {
						o.push('0');
					}
					o.push(hex);
					hex = o.join('');
				}
				return hex;
			}, 
			HexToRGB = function (hex) {
				var hex = parseInt(((hex.indexOf('#') > -1) ? hex.substring(1) : hex), 16);
				return {r: hex >> 16, g: (hex & 0x00FF00) >> 8, b: (hex & 0x0000FF)};
			},
			HexToHSB = function (hex) {
				return RGBToHSB(HexToRGB(hex));
			},
			RGBToHSB = function (rgb) {
				var hsb = {
					h: 0,
					s: 0,
					b: 0
				};
				var min = Math.min(rgb.r, rgb.g, rgb.b);
				var max = Math.max(rgb.r, rgb.g, rgb.b);
				var delta = max - min;
				hsb.b = max;
				if (max != 0) {
					
				}
				hsb.s = max != 0 ? 255 * delta / max : 0;
				if (hsb.s != 0) {
					if (rgb.r == max) {
						hsb.h = (rgb.g - rgb.b) / delta;
					} else if (rgb.g == max) {
						hsb.h = 2 + (rgb.b - rgb.r) / delta;
					} else {
						hsb.h = 4 + (rgb.r - rgb.g) / delta;
					}
				} else {
					hsb.h = -1;
				}
				hsb.h *= 60;
				if (hsb.h < 0) {
					hsb.h += 360;
				}
				hsb.s *= 100/255;
				hsb.b *= 100/255;
				return hsb;
			},
			HSBToRGB = function (hsb) {
				var rgb = {};
				var h = Math.round(hsb.h);
				var s = Math.round(hsb.s*255/100);
				var v = Math.round(hsb.b*255/100);
				if(s == 0) {
					rgb.r = rgb.g = rgb.b = v;
				} else {
					var t1 = v;
					var t2 = (255-s)*v/255;
					var t3 = (t1-t2)*(h%60)/60;
					if(h==360) h = 0;
					if(h<60) {rgb.r=t1;	rgb.b=t2; rgb.g=t2+t3}
					else if(h<120) {rgb.g=t1; rgb.b=t2;	rgb.r=t1-t3}
					else if(h<180) {rgb.g=t1; rgb.r=t2;	rgb.b=t2+t3}
					else if(h<240) {rgb.b=t1; rgb.r=t2;	rgb.g=t1-t3}
					else if(h<300) {rgb.b=t1; rgb.g=t2;	rgb.r=t2+t3}
					else if(h<360) {rgb.r=t1; rgb.g=t2;	rgb.b=t1-t3}
					else {rgb.r=0; rgb.g=0;	rgb.b=0}
				}
				return {r:Math.round(rgb.r), g:Math.round(rgb.g), b:Math.round(rgb.b)};
			},
			RGBToHex = function (rgb) {
				var hex = [
					rgb.r.toString(16),
					rgb.g.toString(16),
					rgb.b.toString(16)
				];
				$.each(hex, function (nr, val) {
					if (val.length == 1) {
						hex[nr] = '0' + val;
					}
				});
				return hex.join('');
			},
			HSBToHex = function (hsb) {
				return RGBToHex(HSBToRGB(hsb));
			},
			restoreOriginal = function () {
				var cal = $(this).parent();
				var col = cal.data('colorpicker').origColor;
				cal.data('colorpicker').color = col;
				fillRGBFields(col, cal.get(0));
				fillHexFields(col, cal.get(0));
				fillHSBFields(col, cal.get(0));
				setSelector(col, cal.get(0));
				setHue(col, cal.get(0));
				setNewColor(col, cal.get(0));
			};
		return {
			init: function (opt) {
				opt = $.extend({}, defaults, opt||{});
				if (typeof opt.color == 'string') {
					opt.color = HexToHSB(opt.color);
				} else if (opt.color.r != undefined && opt.color.g != undefined && opt.color.b != undefined) {
					opt.color = RGBToHSB(opt.color);
				} else if (opt.color.h != undefined && opt.color.s != undefined && opt.color.b != undefined) {
					opt.color = fixHSB(opt.color);
				} else {
					return this;
				}
				return this.each(function () {
					if (!$(this).data('colorpickerId')) {
						var options = $.extend({}, opt);
						options.origColor = opt.color;
						var id = 'collorpicker_' + parseInt(Math.random() * 1000);
						$(this).data('colorpickerId', id);
						var cal = $(tpl).attr('id', id);
						if (options.flat) {
							cal.appendTo(this).show();
						} else {
							cal.appendTo(document.body);
						}
						options.fields = cal
											.find('input')
												.bind('keyup', keyDown)
												.bind('change', change)
												.bind('blur', blur)
												.bind('focus', focus);
						cal
							.find('span').bind('mousedown', downIncrement).end()
							.find('>div.colorpicker_current_color').bind('click', restoreOriginal);
						options.selector = cal.find('div.colorpicker_color').bind('mousedown', downSelector);
						options.selectorIndic = options.selector.find('div div');
						options.el = this;
						options.hue = cal.find('div.colorpicker_hue div');
						cal.find('div.colorpicker_hue').bind('mousedown', downHue);
						options.newColor = cal.find('div.colorpicker_new_color');
						options.currentColor = cal.find('div.colorpicker_current_color');
						cal.data('colorpicker', options);
						cal.find('div.colorpicker_submit')
							.bind('mouseenter', enterSubmit)
							.bind('mouseleave', leaveSubmit)
							.bind('click', clickSubmit);
						fillRGBFields(options.color, cal.get(0));
						fillHSBFields(options.color, cal.get(0));
						fillHexFields(options.color, cal.get(0));
						setHue(options.color, cal.get(0));
						setSelector(options.color, cal.get(0));
						setCurrentColor(options.color, cal.get(0));
						setNewColor(options.color, cal.get(0));
						if (options.flat) {
							cal.css({
								position: 'relative',
								display: 'block'
							});
						} else {
							$(this).bind(options.eventName, show);
						}
					}
				});
			},
			showPicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						show.apply(this);
					}
				});
			},
			hidePicker: function() {
				return this.each( function () {
					if ($(this).data('colorpickerId')) {
						$('#' + $(this).data('colorpickerId')).hide();
					}
				});
			},
			setColor: function(col) {
				if (typeof col == 'string') {
					col = HexToHSB(col);
				} else if (col.r != undefined && col.g != undefined && col.b != undefined) {
					col = RGBToHSB(col);
				} else if (col.h != undefined && col.s != undefined && col.b != undefined) {
					col = fixHSB(col);
				} else {
					return this;
				}
				return this.each(function(){
					if ($(this).data('colorpickerId')) {
						var cal = $('#' + $(this).data('colorpickerId'));
						cal.data('colorpicker').color = col;
						cal.data('colorpicker').origColor = col;
						fillRGBFields(col, cal.get(0));
						fillHSBFields(col, cal.get(0));
						fillHexFields(col, cal.get(0));
						setHue(col, cal.get(0));
						setSelector(col, cal.get(0));
						setCurrentColor(col, cal.get(0));
						setNewColor(col, cal.get(0));
					}
				});
			}
		};
	}();
	$.fn.extend({
		ColorPicker: ColorPicker.init,
		ColorPickerHide: ColorPicker.hidePicker,
		ColorPickerShow: ColorPicker.showPicker,
		ColorPickerSetColor: ColorPicker.setColor
	});
})(jQuery)

/*Array.prototype.has=function(v){
for (i in this){
if (this[i]==v) return i;
}
return false;
}
*/

function getQueryParams(qs) {
    qs = qs.split("+").join(" ");
    var params = {};
    var tokens;

    while (tokens = /[?&]?([^=]+)=([^&]*)/g.exec(qs)) {
        params[decodeURIComponent(tokens[1])]
            = decodeURIComponent(tokens[2]);
    }

    return params;
}

var $_GET = getQueryParams(document.location.search);

function isInteger(s) {
  return (s.toString().search(/^-?[0-9]+$/) == 0);
}

function in_array(val, array)
  {
    for (i in array){
      if (array[i]==val) return true;
      }
    return false;
  }

function fmod (x, y) {
    // http://kevin.vanzonneveld.net
    // +   original by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // *     example 1: fmod(5.7, 1.3);
    // *     returns 1: 0.5
    
    var tmp, tmp2, p = 0, pY = 0, l = 0.0, l2 = 0.0;
    
    tmp = x.toExponential().match(/^.\.?(.*)e(.+)$/);
    p = parseInt(tmp[2], 10)-(tmp[1]+'').length;
    tmp = y.toExponential().match(/^.\.?(.*)e(.+)$/);
    pY = parseInt(tmp[2], 10)-(tmp[1]+'').length;
    
    if (pY > p) {
        p = pY;
    }
    
    tmp2 = (x%y);
    
    if (p < -100 || p > 20) {
        // toFixed will give an out of bound error so we fix it like this:
        l  = Math.round(Math.log(tmp2)/Math.log(10));
        l2 = Math.pow(10, l);
        
        return (tmp2 / l2).toFixed(l-p)*l2;
    } else {
        return parseFloat(tmp2.toFixed(-p));
    }
}

function getImgSize(imgSrc)
{
var newImg = new Image();
newImg.src = imgSrc;
//var height = newImg.height;
//var width = newImg.width;
imgSize = new Array(newImg.width, newImg.height);
return imgSize;
}

function removePx(string)
  {
    return string.replace("px", "");
  }

$.maxZIndex = $.fn.maxZIndex = function(opt) {
    /// <summary>
    /// Returns the max zOrder in the document (no parameter)
    /// Sets max zOrder by passing a non-zero number
    /// which gets added to the highest zOrder.
    /// </summary>    
    /// <param name="opt" type="object">
    /// inc: increment value, 
    /// group: selector for zIndex elements to find max for
    /// </param>
    /// <returns type="jQuery" />
    var def = { inc: 10, group: "*" };
    $.extend(def, opt);    
    var zmax = 0;
    $(def.group).each(function() {
        var cur = parseInt($(this).css('z-index'));
        zmax = cur > zmax ? cur : zmax;
    });
    if (!this.jquery)
        return zmax;

    return this.each(function() {
        zmax += def.inc;
        $(this).css("z-index", zmax);
    });
}


function findHighestZIndex(elem)
{
  var elems = document.getElementsByTagName(elem);
  var highest = 0;
  for (var i = 0; i < elems.length; i++)
  {
    var zindex=document.defaultView.getComputedStyle(elems[i],null).getPropertyValue("z-index");
    if ((zindex > highest) && (zindex != 'auto'))
    {
      highest = zindex;
    }
  }
  return highest;
}


function debugLog(text)
  {
    $("body").append('<li>' + text + '</li>');
  }

function o(id) {return document.getElementById(id);} //get element by ID

function modFilePath(path)
  {
    return path.substring(0,1) == "." ? path.substring(1) : path;
  }

function realFilePath(path)
  {
    return path.substring(0,1) == "/" ? "." + path : path;
  }

function FindKey(arr, key, value)
  {
    for(x in arr)
      {
        if(arr[x][key]==value){return x;}
      }
    return 'undefined';
  }

function arrayLength(array)
  {
    var count = 0; 
    for(x in array)
      {
        count++;
      }
    return count;
  }

function arrMaxVal(arr, key)
  {
    var max=0;
    for(x in arr)
      {
        if (arr[x][key] > max) {max = arr[x][key];}
      }
    return max;
  }

function strrpos (haystack, needle, offset) {
    var i = (haystack+'').lastIndexOf( needle, offset ); // returns -1
    return i >= 0 ? i : false;
}

function isNumeric(value) {
  if (value == null || !value.toString().match(/^[-]?\d*\.?\d*$/)) return false;
  return true;
}

String.prototype.trim = function()
  {
    return this.replace(/(^\s*)|(\s*$)/g, "");
  }

function isInt(x) { 
   var y=parseInt(x); 
   if (isNaN(y)) return false; 
   return x==y && x.toString()==y.toString(); 
 } 


function ShowHTML(element_id, html)
  {
    try{document.getElementById(element_id).innerHTML="";}
    catch(e){alert("Objekt s ID "+element_id+" nelze najt!");}
    $("#"+element_id).append(html);
  }
  
function DisplayHTML(element_id, html)
  {
    try{document.getElementById(element_id).innerHTML="";}
    catch(e){alert("Objekt s ID "+element_id+" nelze najt!");}
    $("#"+element_id).append(html);
  }
  
function AddHTML(element_id, html)
  {
   $("#"+element_id).append(html);
  }
 
 
function L(group, name)
  {
    try
      {
        return Label[group][name];
      }
    catch(e)
      {
      
      }
  } 
var Label = new Array();




$(document).ready(function() {
  
  $(".field.f_color").each(function(){
    fieldType_Color({showField: !$(this).hasClass("field_disabled"), containerId: "container_"+$(this).attr("id"),fieldName: $(this).attr("id"), fieldColor: $(this).find(".ff input").attr("value")});
  });
});

function fieldType_Color(settings)
  {
    settings = jQuery.extend({
      
      fieldName: '',
      containerId: '',
      showField: true,
      fieldColor: '#FFFFFF',
      
      labelSelectColor: 'Vyberte barvu',
      labelOpenColorPicker: 'Zvolit barvu z palety'
      
    },settings);
    
    initialize();
    
    if(settings.showField){show();}
    else{remove();}
    
    function initialize()
      {
        $('#' + settings.fieldName + ' label input').unbind("click").click(function(){
          if($(this).attr("checked")){show();}
          else{remove();}
          //$('#' + settings.fieldName).toggleClass("field_disabled");
        });
        
        settings.container = $('#' + settings.containerId);
      }
    
    function show()
      {
        settings.container.html('');
        settings.container.append('<a href="javascript:void(0);" title="' + settings.labelOpenColorPicker + '"><div style="background-color: ' + settings.fieldColor + '" id="block_color_' + settings.fieldName + '"></div><span>' + settings.labelSelectColor + '</span></a>');
        settings.container.append('<input class="input_hidden" type="hidden" name="' + settings.fieldName + '" id="f_' + settings.fieldName + '" value="' + settings.fieldColor + '" />');
        settings.container.ColorPicker(
            {
                color: settings.fieldColor,
                onShow: function (colpkr) {$(colpkr).fadeIn(500);return false;},
                onHide: function (colpkr) {$('#f_' + settings.fieldName).trigger("validateField");$(colpkr).fadeOut(500);return false;},
                onChange: function (hsb, hex, rgb) {
                  $('#block_color_' + settings.fieldName).css('backgroundColor', '#' + hex);
                  $('#f_' + settings.fieldName).attr("value", '#' + hex);
                }
            });    
      }
      
    function remove()
      {
        $('#' + settings.fieldName + ' .ff').html('');
      }
  
  }



$(document).ready(function() {
  
  $(".field.f_date").each(function(){
    fieldType_Date({showField: !$(this).hasClass("field_disabled"), containerId: "container_"+$(this).attr("id"),fieldName: $(this).attr("id"), fieldType: 'date', fieldDate: $(this).find(".ff input").attr("value")});
  });
  $(".field.f_datetime").each(function(){
    fieldType_Date({showField: !$(this).hasClass("field_disabled"), containerId: "container_"+$(this).attr("id"),fieldName: $(this).attr("id"), fieldType: 'datetime', fieldDate: $(this).find(".ff input").attr("value")});
  });

});

function fieldType_Date(settings)
  {
    settings = jQuery.extend({
      
      fieldName: '',
      containerId: '',
      showField: true,
      fieldType: 'datetime',
      fieldDate: '0000-00-00 00:00:00'
      
    },settings);
    
    initialize();
    
    if(settings.showField){show();}
    else{remove();}
    
    function initialize()
      {
        $('#' + settings.fieldName + ' label input').unbind("click").click(function(){
          if($(this).attr("checked")){show();}
          else{remove();}
        });
        
        settings.container = $('#' + settings.containerId);
      }
    
    function show()
      {
        if(settings.fieldDate == '0000-00-00 00:00:00')
          {
            exd = new Date(); 
            settings.fieldDate = exd.getFullYear()+'-'+(exd.getMonth()+1)+'-'+exd.getDate()+' '+exd.getHours()+':'+exd.getMinutes()+':'+exd.getSeconds();
          }
        
        settings.container.html('');
        settings.container.append('<a href="javascript:void(0);" id="f_' + settings.fieldName + '_link"></a>');
        settings.container.append('<input class="input_hidden" type="hidden" name="' + settings.fieldName + '" id="f_' + settings.fieldName + '" value="' + settings.fieldDate + '" />');
        
        switch(settings.fieldType)
          {
            case "datetime":
              Calendar.setup(
                {
                  inputField     :    "f_" + settings.fieldName,     
                  ifFormat       :    "%Y-%m-%d %I:%M:%S",     
                  displayArea    :    'f_' + settings.fieldName  + '_link',      
                  daFormat       :    "%d. %B %Y %I:%M",
                  align          :    "Tl", 
                  showsTime      :    true,
                  onClose        :    function(){$('#f_' + settings.fieldName + '_link').trigger("validateField");},
                  timeFormat     :    "24", 
                  singleClick    :    true
                });
                $('#f_' + settings.fieldName + '_link').append(Date.parseDate(settings.fieldDate,"%Y-%m-%d %I:%M:%S").print("%d. %B %Y %I:%M"));
                break;
              
            case "date":
              Calendar.setup(
                {
                  inputField     :    "f_" + settings.fieldName,     
                  ifFormat       :    "%Y-%m-%d",     
                  displayArea    :    'f_' + settings.fieldName  + '_link',      
                  daFormat       :    "%d. %B %Y",
                  align          :    "Tl", 
                  showsTime      :    false,
                  onClose        :    function(){$('#f_' + settings.fieldName + '_link').trigger("validateField");},
                  timeFormat     :    "24", 
                  singleClick    :    true
                });
                $('#f_' + settings.fieldName + '_link').append(Date.parseDate(settings.fieldDate,"%Y-%m-%d").print("%d. %B %Y"));
                break;
          }
      }
      
    function remove()
      {
        $('#' + settings.fieldName + ' .ff').html('');
      }
  
  }



$(document).ready(function() {
  $(".f_gallery").each(function(){
    fieldType_File({showField: !$(this).hasClass("field_disabled"), fieldName: $(this).attr("id"),fieldType: "gallery",containerId: "container_"+$(this).attr("id"),fieldFile: FieldFile[$(this).attr("id")]});
  });
  $(".f_files").each(function(){
    fieldType_File({showField: !$(this).hasClass("field_disabled"), fieldName: $(this).attr("id"),fieldType: "files",containerId: "container_"+$(this).attr("id"),fieldFile: FieldFile[$(this).attr("id")]});
  });
  $(".f_file").each(function(){
    fieldType_File({showField: !$(this).hasClass("field_disabled"), fieldName: $(this).attr("id"),fieldType: "file",containerId: "container_"+$(this).attr("id"),fieldFile: FieldFile[$(this).attr("id")]});
  });
  $(".f_image").each(function(){
    fieldType_File({showField: !$(this).hasClass("field_disabled"), fieldName: $(this).attr("id"),fieldType: "image",containerId: "container_"+$(this).attr("id"),fieldFile: FieldFile[$(this).attr("id")]});
  });
}); 

var FLD_FILEMANAGER = "/scripts/components/system/files/";
var FieldFile = new Array();

function fieldType_File(settings)
  {
    settings = jQuery.extend({
      
      fieldName: '',
      fieldType: 'image',
      containerId: '',
      fieldFile: new Array(),
      hiddenFields: '',
      showField: true,
      
      labelOpenManager: 'Otevřít průzkumník',
      labelManager: 'Průzkumník', 
      labelNoFilesSelected: 'Není vybrán žádný soubor',  
      labelRotateImageMinus: 'Otočit obrázek proti směru hodinových ručiček',
      labelRotateImagePlus: 'Otočit obrázek po směru hodinových ručiček',
      labelRotateMinus: 'Otočit proti směru',
      labelRotatePlus: 'Otočit po směru',
      labelRemoveThisFile: 'Odebrat tento soubor',
      labelRemove: 'Odebrat',
      labelMoveItemUp: 'Posunout nahoru',
      labelMoveItemDown: 'Posunout dolů',
      labelMoveUp: 'Nahoru',
      labelMoveDown: 'Dolů',
      labelThumb: 'Náhled',
      labelMainImage: 'Hlavní',
      labelAddFiles: 'Přidat soubory',
      labelSelectFile: 'Vybrat soubor',
      labelFileName: 'Název',
      labelFileDescription: 'Popis',
      imagesOnLine: 6,
      
      idFilesTable: 'default_filestable',
      
      pathIconManager:  FLD_FILEMANAGER + 'icon/ico_filemanager_40x40.png',
      pathDefaultIcon: FLD_FILEMANAGER + 'icon/white/ico_file_20x20.png',
      maxWidth: 126,
      maxHeight: 110
      
		},settings);
		
		initialize();
		
    if(settings.showField){show();}
    else{remove();}
    
    function initialize()
      {
        $('#' + settings.fieldName + ' label input').unbind("click").click(function(){
          if($(this).attr("checked")){show();}
          else{remove();}
          //$('#' + settings.fieldName).toggleClass("field_disabled");
        });
        
        
        settings.idFilesTable = settings.fieldName + '_filestable';
        settings.idButton = settings.fieldName + '_buttonManager';
        settings.idList = settings.fieldName + '_list';
        settings.container = $('#' + settings.containerId);
        settings.multiple = (settings.fieldType == "files" || settings.fieldType == "gallery") ? true : false;
        
        for(x in settings.fieldFile)
          {
            if(settings.fieldFile[x]["order"] == 0){repairFileOrder();break;}
          }
      }
    
    function show()
      {
        settings.container.append('<a class="butt_text bt_filemanager" id="' + settings.idButton + '" title="' + settings.labelOpenManager+ '" href="javascript: void(0);">'+(settings.fieldType == 'gallery' || settings.fieldType == 'files' ? settings.labelAddFiles : settings.labelSelectFile)+'</a>');
        settings.container.append('<div class="block_fileslist bf_'+settings.fieldType+'" id="'+settings.idList+'"></div>');
        showList();
        $('#'+settings.idButton).click(function(){showManager(settings.fieldType);});
      }
    
    function remove()
      {
        settings.container.html('');
      }
    
    function showList()
      {
        var image_no = 1;
        settings.hiddenFields = '';
        $("#" + settings.idList).html('');
        
        settings.fieldFile.sort(function(a, b){return a["order"]-b["order"];});
        
        if(!arrayLength(settings.fieldFile))
          {
            $("#" + settings.idList).append('<strong class="empty_note">' + settings.labelNoFilesSelected + '</strong>');
          }
        else
          {
            switch (settings.fieldType)
              {
                case "file":
                case "files":
                  //$("#" + settings.idList).append('<table cellspacing="0" class="table_fileslist" id="' + settings.idFilesTable + '"></table>');
                  for(x in settings.fieldFile)
                    {
                      showFile(x, image_no);
                      image_no++;
                    }
                  break;
                
                case "image":
                case "gallery":
                  for (x in settings.fieldFile)
                    {
                      showImage(x, image_no);
                      image_no++;
                    }
                  $("#" + settings.idList).append('<div class="cleaner"></div>');
                  break;
              }
            $("#" + settings.idList).append(settings.hiddenFields);
          }
        
        updateThumbnails();
      }
    
    function showManager(type, key)
      {
        var key = key || ''; 
        var filter = new Array();
        var multiple = false;
        var path = '';
        sf = new Array();
        
        if(settings.fieldFile[0])
          {
            path = settings.fieldFile[0]["full"];
          }
        else
          {
            path = '';
          }
        
        switch(type)
          {
            case 'image': 
              
              //sf[0] = path;
              multiple = false;
              filter = ["jpg", "jpeg", "bmp", "gif", "png"];
              break;
            case 'gallery': 
              multiple = true;
              filter = ["jpg", "jpeg", "bmp", "gif", "png"];
              break;
            case 'thumb': 
              multiple = false;
              filter = ["jpg", "jpeg", "bmp", "gif", "png"];
              break;
            case 'file':
              //if(settings.fieldFile[0]){path = settings.fieldFile[0]["full"];}else{path = '';}
              
              //sf[0] = path;
              multiple = false;
              filter = new Array();
              break;
            case 'files':
            default: 
              multiple = true;
              filter = new Array();
              break;
          }
        
        ShowDialogWindow({
          windowID: 'dlg_file', 
          title: settings.labelManager, 
          width: 900, 
          height: 600, 
          callin: function(win){
          
          fileManager({
            //selectedFile: sf,
            Path: path,
            con: win,
            multiple: true,
            Filter: filter
          });
          
          }, 
          callback: function(win){
            switch(type)
              {
                case "thumb": returnThumbnail(win,key);break;
                default: returnFile(win); break;
              } 
            }
          });
      }
    
    function maxImageSize(width, height)
      {
        if(width>=height)
          {
            width = settings.maxWidth; 
            height = (height/width)*settings.maxHeight; 
          }
        else
          {
            width = (width/height)*settings.maxWidth; 
            height = settings.maxHeight; 
          }
        imgSize = new Array(width,height);
        return imgSize;
      }
    
    function showImage(x, arr_key)
      {
        id_blockItem = settings.fieldName + '_item_' + x;
        
        path_thumb = modFilePath((settings.fieldFile[x]["thb"].length ? settings.fieldFile[x]["thb"] : settings.fieldFile[x]["full"])) + '?unique=' + new Date().valueOf();
        
        $("#" + settings.idList).append(
          '\n<div class="block_image' + ((arr_key%settings.imagesOnLine) == 0 ? ' bi_last' : '') + '" id="' + id_blockItem + '">' + 
          '\n<div class="bi_image">' + 
          '\n<img src="' + path_thumb + '" alt="' + settings.fieldFile[x]["caption"] + '" />' + 
          '\n<a class="butt_small bs_rotate_minus" href="javascript:void(0);" title="'+settings.labelRotateImageMinus+'">'+settings.labelRotateMinus+'</a>' + 
          '\n<a class="butt_small bs_rotate_plus" href="javascript:void(0);" title="'+settings.labelRotateImagePlus+'">'+settings.labelRotatePlus+'</a>' +
          '\n</div>' + 
          '<input class="input_default input_caption" type="text" name="'+settings.fieldName+'_caption['+arr_key+']" value="' + (settings.fieldFile[x]["caption"].length ? settings.fieldFile[x]["caption"] : settings.labelFileName) + '" />' +
          '\n<textarea class="input_description" name="'+settings.fieldName+'_description['+arr_key+']">'+(settings.fieldFile[x]["description"].length ? settings.fieldFile[x]["description"] : settings.labelFileDescription)+'</textarea>' +
          
          '\n<a href="javascript:void(0);" id="' + id_blockItem + '_butt_remove" class="butt_small bs_remove" title="' + settings.labelRemoveThisFile + '">'+settings.labelRemove+'</a>' +
          
          (arrayLength(settings.fieldFile)>1 ? 
              '\n<input class="input_radio" type="radio"' + (settings.fieldFile[x]["switch_main"] == 1 ? ' checked="checked"' : '') + ' name="'+settings.fieldName+'_switch_mainimage" value="'+settings.fieldFile[x]["id"]+'" /><label for="'+settings.fieldName+'_switch_mainimage">'+settings.labelMainImage+'</label>' + 
              (settings.fieldFile[x]["order"] > 1 ? '\n<a href="javascript:void(0);" id="' + id_blockItem + '_butt_moveleft" class="butt_small bs_moveleft" title="'+settings.labelMoveItemUp+'"><span>'+settings.labelMoveUp+'</span></a>' : '<span class="butt_small bs_moveleft">'+settings.labelMoveUp+'</span>') + 
              (settings.fieldFile[x]["order"] < arrayLength(settings.fieldFile) ? '\n<a href="javascript:void(0);" id="' + id_blockItem + '_butt_moveright" class="butt_small bs_moveright" title="'+settings.labelMoveItemDown+'"><span>'+settings.labelMoveDown+'</span></a>' : '<span class="butt_small bs_moveright">'+settings.labelMoveDown+'</span>')
              :
              '') + 
          
          '\n</div>\n');
        
        //imgSize = getImgSize(realFilePath(path_thumb));
        
        //var img = $('#' + id_blockItem + ' img');
        //var width = obj.clientWidth;
        //var height = obj.clientHeight;
        
        //maxSize = maxImageSize(width, height);
        
        //var width = img.naturalWidth;
        //var height = img.naturalHeight;
        
       // alert(width + "x" + height + ' -- ' + $('#' + id_blockItem + ' img').width() + "x"+ $('#' + id_blockItem + ' img').height());
        
        //$('#' + id_blockItem + ' img').width(maxSize[0]).height(maxSize[1]);
        $('#' + id_blockItem + ' .input_caption').focus(function(){if(!settings.fieldFile[x]['caption'].length){this.value = '';}});
        $('#' + id_blockItem + ' .input_caption').blur(function(){settings.fieldFile[x]['caption']=this.value;});
        $('#' + id_blockItem + ' .input_description').focus(function(){if(!settings.fieldFile[x]['description'].length){this.value = '';}});
        $('#' + id_blockItem + ' .input_description').blur(function(){settings.fieldFile[x]['description']=this.value;});
        
        $('#' + id_blockItem + ' .bs_remove').click(function(){removeFile(x);});
        $('#' + id_blockItem + ' .bs_moveleft').click(function(){moveFile(x, 0);});
        $('#' + id_blockItem + ' .bs_moveright').click(function(){moveFile(x, 1);});
        $('#' + id_blockItem + ' .bs_rotate_plus').click(function(){rotateImage(settings.fieldFile[x]["full"], 270);});
        $('#' + id_blockItem + ' .bs_rotate_minus').click(function(){rotateImage(settings.fieldFile[x]["full"], 90);});
        
        settings.hiddenFields +=
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_datetime['+arr_key+']" value="'+settings.fieldFile[x]["datetime"]+'" />' + 
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_path['+arr_key+']" value="'+settings.fieldFile[x]["full"]+'" />' + 
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_order['+arr_key+']" value="'+settings.fieldFile[x]["order"]+'" />' + 
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_id['+arr_key+']" value="'+settings.fieldFile[x]["id"]+'" />' + 
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_thb_path['+arr_key+']" value="'+settings.fieldFile[x]["thb"]+'" />' + 
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_new_thb_path['+arr_key+']" value="'+settings.fieldFile[x]["new_thb"]+'" />';
      }  
    
    function showFile(x, arr_key)
      {
        id_blockItem = settings.fieldName + '_item_' + x;
        
        path_icon = modFilePath(FLD_FILEMANAGER + 'icon/white/ico_' + settings.fieldFile[x]["type"] + '_20x20.png');
        
        //if(settings.fieldFile[x]["new_thb"].length){alert(settings.fieldFile[x]["new_thb"]);}
        
        path_thumb = modFilePath((settings.fieldFile[x]["new_thb"].length ? settings.fieldFile[x]["new_thb"] : settings.fieldFile[x]["thb"]));
        
        $("#" + settings.idList).append(
          '\n<div class="block_file" id="' + id_blockItem + '">' +
          (settings.fieldFile[x]["order"] > 1 ? '<a href="javascript:void(0);" class="butt_small bs_moveup" title="'+settings.labelMoveItemUp+'"><span>'+settings.labelMoveUp+'</span></a>' : '<span class="butt_small bs_moveup">'+settings.labelMoveUp+'</span>') +
          (settings.fieldFile[x]["order"] < arrayLength(settings.fieldFile) ? '<a href="javascript:void(0);" class="butt_small bs_movedown" title="'+settings.labelMoveItemDown+'"><span>'+settings.labelMoveDown+'</span></a>' : '<span class="butt_small bs_movedown">'+settings.labelMoveDown+'</span>') +
          '\n<img class="ico_small" src="' + (path_icon ? path_icon : settings.pathDefaultIcon ) + '" />' +
          '</td>' +
          '\n<strong>' + settings.fieldFile[x]["name"] + '</strong>' +
          '<input class="input_default input_caption" type="text" name="'+settings.fieldName+'_caption['+arr_key+']" value="' + (settings.fieldFile[x]["caption"].length ? settings.fieldFile[x]["caption"] : settings.labelFileName) + '" />' +
          '\n<input class="input_default input_description" type="text" name="'+settings.fieldName+'_description['+arr_key+']" value="'+(settings.fieldFile[x]["description"].length ? settings.fieldFile[x]["description"] : settings.labelFileDescription)+'" />' +
          '\n<a class="butt_small bs_remove" href="javascript:void(0);" title="' + settings.labelRemoveThisFile + '">'+settings.labelRemove+'</a>' +
          '\n<a class="butt_small bs_thumbnail" href="javascript:void(0);" title="' + path_thumb + '">' + settings.labelThumb + '</a>' +
          '\n</div>'
          );
        
        $('#' + id_blockItem + ' .input_caption').focus(function(){if(!settings.fieldFile[x]['caption'].length){this.value = '';}});
        $('#' + id_blockItem + ' .input_caption').blur(function(){settings.fieldFile[x]['caption']=this.value;});
        $('#' + id_blockItem + ' .input_description').focus(function(){if(!settings.fieldFile[x]['description'].length){this.value = '';}});
        $('#' + id_blockItem + ' .input_description').blur(function(){settings.fieldFile[x]['description']=this.value;});
        $('#' + id_blockItem + ' .bs_remove').click(function(){removeFile(x);});
        $('#' + id_blockItem + ' .bs_moveup').click(function(){moveFile(x, 0);});
        $('#' + id_blockItem + ' .bs_movedown').click(function(){moveFile(x, 1);});
        $('#' + id_blockItem + ' .bs_thumbnail').click(function(){showManager("thumb", x);});
        
        settings.hiddenFields += 
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_datetime['+arr_key+']" value="'+settings.fieldFile[x]["datetime"]+'" />' + 
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_path['+arr_key+']" value="'+settings.fieldFile[x]["full"]+'" />' + 
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_order['+arr_key+']" value="'+settings.fieldFile[x]["order"]+'" />' + 
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_id['+arr_key+']" value="'+settings.fieldFile[x]["id"]+'" />' + 
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_thb_path['+arr_key+']" value="'+settings.fieldFile[x]["thb"]+'" />' + 
          '\n<input class="input_hidden" type="hidden" name="'+settings.fieldName+'_new_thb_path['+arr_key+']" value="'+settings.fieldFile[x]["new_thb"]+'" />';
      }
  
    function rotateImage(file_path, degrees)
      {
        $.post("/index.php", {'initialize_for_ajax' : 'true', 'file': './scripts/components/system/files/mods/mod_rotate_image.php', 'file_path': file_path, 'degrees': degrees}, function(data){showList();});
      }
  
    function removeFile(x)
      {
        for(y in settings.fieldFile)
          {
            if(settings.fieldFile[y]["order"]>settings.fieldFile[x]["order"]) {settings.fieldFile[y]["order"]--;}
          }
        delete settings.fieldFile[x];
        showList();
      }
  
    function moveFile(x, direction)
      {
        nextItem = FindKey(settings.fieldFile, "order", (parseInt(settings.fieldFile[x]["order"])+1));
        peviousItem = FindKey(settings.fieldFile, "order", (parseInt(settings.fieldFile[x]["order"])-1));
        if(direction && nextItem!='undefined')
          {
            settings.fieldFile[x]["order"]++;
            settings.fieldFile[nextItem]["order"]--;
          }
        else if(!direction && peviousItem!='undefined')
          {
            settings.fieldFile[x]["order"]--;
            settings.fieldFile[peviousItem]["order"]++;
          }
        
        showList();
      }
    
    function addFile(path)
      {
        var temp_array = new Array();
        var file_type = path.split(".");
        var file_name = path.split("/");
    
        temp_array["id"]=0;
        temp_array["ico"]="";
        temp_array["type"]=file_type.pop();
        temp_array["name"]=file_name.pop();
        temp_array["caption"]=''; //settings.labelFileName;
        temp_array["description"]=''; //settings.labelFileDescription;
        temp_array["order"]=settings.multiple ? parseInt(arrMaxVal(settings.fieldFile, "order"))+1 : 1;
        temp_array["full"]=path;
        temp_array["thb"]=''; 
        temp_array["new_thb"] = path;
        temp_array["datetime"] = '';
        settings.fieldFile[(settings.multiple ? settings.fieldFile.length : 0)]=temp_array;
      }
     
    function returnFile(win)
      {
        $(win).find("input[name=selected_file]").each(function(){
          addFile(realFilePath($(this).attr("value")));
        });
        //for (a = 0; win.contents().find('#selected_file_'+a).length; a++)
        //  {
        //    if(win.contents().find('#selected_file_'+a).attr("checked"))
        //      {
        //        addFile(win.contents().find('#selected_file_'+a).attr("value"));
        //      }
        // }
        
        showList();
      }
      
    function returnThumbnail(win, x)
      {
        var found = false;
        //for (a = 0; win.contents().find('#selected_file_'+a).length; a++)
        $(win).contents().find("input[name=selected_file]").each(function()
          {
            settings.fieldFile[x]["new_thb"] = modFilePath($(this).attr("value"));
            found = true;
          });
        if(!found)
          {  
            settings.fieldFile[x]["thb"] = '';
            settings.fieldFile[x]["new_thb"] = '';
          }
        showList();
        return found;
      } 
    
    function repairFileOrder()
      {
        var order = 1;
        for(x in settings.fieldFile)
          {
            settings.fieldFile[x]["order"] = order;
            order++;
          }
      }
    
    function updateThumbnails()
      {
        $('#' + settings.containerId + " .block_fileslist a.bs_thumbnail").easyTooltip({
          showThumb: true,
          thumbParam: "title"
        });
      }
  }


$(document).ready(function() {
  
  $(".field.f_html").each(function(){
    fieldType_Html({showField: !$(this).hasClass("field_disabled"), fieldType: 'advanced', containerId: "container_"+$(this).attr("id"), fieldHTML: $(this).find("textarea").text(), fieldName: $(this).attr("id")});
  });
  
  $(".field.f_lighthtml").each(function(){
    fieldType_Html({showField: !$(this).hasClass("field_disabled"), fieldType: 'simple', containerId: "container_"+$(this).attr("id"), fieldHTML: $(this).find("textarea").text(), fieldName: $(this).attr("id")});
  });


        //tinyMCE.init({

        


});

function fieldType_Html(settings)
  {
    settings = jQuery.extend({
      
      fieldName: '',
      fieldHTML: '',
      showField: true,
      fieldType: 'advanced',
      containerId: ''
      
    },settings);
    
    initialize();
    
    if(settings.showField){show();}
    else{remove();}
    
    function initialize()
      {
        $('#' + settings.fieldName + ' label input').unbind("click").click(function(){
          if($(this).attr("checked")){show();}
          else{remove();}
        });
        settings.container = $('#' + settings.containerId);
      }
    
    function show()
      {
        settings.container.html('');
        settings.container.append('<div class="block_editor"><textarea name="' + settings.fieldName + '" id="f_' + settings.fieldName + '">'+settings.fieldHTML+'</textarea></div>');
        
        switch(settings.fieldType)
          {
            case 'advanced':
              settings.container.find('textarea').tinymce({
			
              //debug: true,
              cleanup : true,
              body_class : 'body_html_editor',
              extended_valid_elements : "module[*],field[*],page[*],template[*],embed[*],iframe[*]",
              //custom_elements: 'module,template,field,page',
              script_url : '/scripts/js/tiny_mce/tiny_mce.js',
              theme : "advanced",
			        language: "cs",
			        plugins : "safari,pagebreak,style,layer,table,save,advhr,advimage,advlink,emotions,iespell,inlinepopups,insertdatetime,preview,media,searchreplace,print,contextmenu,paste,directionality,fullscreen,noneditable,visualchars,nonbreaking,xhtmlxtras,template",
              relative_urls : false,
              convert_urls : false,
			         theme_advanced_buttons1 : "bold,italic,underline,strikethrough,|,justifyleft,justifycenter,justifyright,justifyfull,styleselect,formatselect,fontsizeselect",
			         theme_advanced_buttons2 : "cut,copy,paste,pastetext,pasteword,|,search,replace,|,bullist,numlist,|,outdent,indent,blockquote,|,undo,redo,|,link,unlink,anchor,image,cleanup,code,|,insertdate,inserttime,preview,|,forecolor,backcolor",
			         theme_advanced_buttons3 : "tablecontrols,|,hr,removeformat,visualaid,|,sub,sup,|,charmap,emotions,iespell,media,advhr,|,print,|,ltr,rtl,|,fullscreen",
			         theme_advanced_buttons4 : "insertlayer,moveforward,movebackward,absolute,|,styleprops,|,cite,abbr,acronym,del,ins,attribs,|,visualchars,nonbreaking,template,pagebreak",
			         theme_advanced_toolbar_location : "top",
			         theme_advanced_toolbar_align : "left",
			         theme_advanced_statusbar_location : "bottom",
			         theme_advanced_resizing : false,
			         //width: 930,
              height: 800,
              file_browser_callback : 'mceFileBrowser',
			         content_css : "/templates/cpr/css/screen/common.css",
			         //remove_trailing_nbsp : false,
			         entity_encoding : "raw"
			     

              // Drop lists for link/image/media/template dialogs
			        //template_external_list_url : "lists/template_list.js",
			         //external_link_list_url : "lists/link_list.js",
			         //external_image_list_url : "lists/image_list.js",
			         //media_external_list_url : "lists/media_list.js",
      
              });
              //settings.container.find('textarea').tinymce().getBody().addClass('body_html_editor');
            break;
          case 'simple':
            settings.container.find('textarea').tinymce({
			
              cleanup : true,
              valid_elements: "b,i,u,a,s,ol,ul,li,sup,sub",
              extended_valid_elements : "module[*],field[*],page[*],template[*],embed[*]",
              inline_styles : false,
              script_url : FLD_JS+'tiny_mce/tiny_mce.js',
              theme : "advanced",
              relative_urls : false,
              convert_urls : false,
			        theme_advanced_buttons1 : "bold,italic,underline,strikethrough,sub,sup,link,unlink,bullist,numlist,blockquote,undo", 
              theme_advanced_buttons2 : "", 
              theme_advanced_buttons3 : "", 

              entity_encoding : "raw",
			        height: 130,
			        language: "cs",
			     
			        content_css : "/templates/output/common/css/screen/common.css"
			     

                });
              break;
        //  case default:
		    }
        
      
      }
      
    function remove()
      {
        $('#' + settings.fieldName + ' .ff').html('');
      }
  
  }
	
function mceFileBrowser (field_name, url, type, win) {

    var flt = field_name=="src" ? ["jpg", "jpeg", "bmp", "gif", "png"] : new Array();
    
    ShowDialogWindow({
          windowID: 'dlg_file', 
          title: 'Průzkumník', 
          width: 800, 
          height: 500, 
          callin: function(w){
          
            fileManager({
            con: w,
            multiple: false,
            Filter: flt
          });
          
          }, 
          callback: function(w){
            win.document.getElementById(field_name).value = modFilePath($(w).find("input[name=selected_file]").attr("value"));
            }
          });
    
    return false;
  }


$(document).ready(function() {
  
  $(".field.f_password").each(function(){
    fieldType_Password({showField: !$(this).hasClass("field_disabled"), containerId: "container_"+$(this).attr("id"),fieldName: $(this).attr("id"), fieldValue: $(this).find(".ff input").attr("value")});
  });
});

function fieldType_Password(settings)
  {
    settings = jQuery.extend({
      
      fieldName: '',
      containerId: '',
      showField: true,
      fieldValue: '',
      
      labelRetypePassword: 'Heslo znovu'
      
    },settings);
    
    initialize();
    
    if(settings.showField){show();}
    else{remove();}
    
    function initialize()
      {
        $('#' + settings.fieldName + ' label input').unbind("click").click(function(){
          if($(this).attr("checked")){show();}
          else{remove();}
          //$('#' + settings.fieldName).toggleClass("field_disabled");
        });
        
        settings.container = $('#' + settings.containerId);
      }
    
    function show()
      {
        settings.container.html('');
        settings.container.append(
          '<input class="input_password" type="password" name="new_'+settings.fieldName + '" id="f_new_'+settings.fieldName+'" value="" />' + 
          '<span>'+settings.labelRetypePassword+':</span><input class="input_password" type="password" name="new_'+settings.fieldName + '_check" id=\"f_new_'+settings.fieldName + '_check" value="" />'
        );
      }
      
    function remove()
      {
        $('#' + settings.fieldName + ' .ff').html('<input type="hidden" name="'+settings.fieldName+'" value="'+settings.fieldValue+'" />');
      }
  
  }



$(document).ready(function() {
  
  $(".field.f_sex").each(function(){
    fieldType_Sex({showField: !$(this).hasClass("field_disabled"), containerId: "container_"+$(this).attr("id"),fieldName: $(this).attr("id"), fieldValue: $(this).find(".ff input").attr("value")});
  });
});

function fieldType_Sex(settings)
  {
    settings = jQuery.extend({
      
      fieldName: '',
      containerId: '',
      showField: true,
      fieldValue: '',
      
      labelMale: 'Muž',
      labelFemale: 'Žena'
      
    },settings);
    
    initialize();
    
    if(settings.showField){show();}
    else{remove();}
    
    function initialize()
      {
        $('#' + settings.fieldName + ' label input').unbind("click").click(function(){
          if($(this).attr("checked")){show();}
          else{remove();}
        });
        
        settings.container = $('#' + settings.containerId);
        //alert(settings.fieldValue);
      }
    
    function show()
      {
        //alert(settings.fieldValue);
        settings.container.html('');
        settings.container.append(
          '<label for="'+settings.fieldName+'_radio">'+settings.labelFemale+'<input class="input_radio" type="radio" name="'+settings.fieldName + '_radio" id="f_'+settings.fieldName+'_0" value="0" '+(settings.fieldValue == 0 ? 'checked="checked"' : '')+' /></label>' + 
          '<label for="'+settings.fieldName+'_radio">'+settings.labelMale+'<input class="input_radio" type="radio" name="'+settings.fieldName + '_radio" id="f_'+settings.fieldName+'_1" value="1" '+(settings.fieldValue == 1 ? 'checked="checked"' : '')+' /></label>' +
          '<input class="input_hidden" type="hidden" name="'+settings.fieldName+'" id="f_'+settings.fieldName+'" value="' + settings.fieldValue + '" />'
        );
        $(settings.container).find("input[type='radio']").click(function(){$("#f_"+settings.fieldName).attr("value", $(this).attr("value"));});
      }
      
    function remove()
      {
        $('#' + settings.fieldName + ' .ff').html('');
      }
  
  }


$(document).ready(function() {
  $(".f_shoplist").each(function(){
    fieldType_ShopList({Obj: $(this), showField: !$(this).hasClass("field_disabled"), fieldName: $(this).attr("id"),containerId: "container_"+$(this).attr("id"),fieldItem: OrderItem});
  });
}); 

//var Structure = new Array();
//var StructureField = new Array();

function fieldType_ShopList(settings)
  {
    settings = jQuery.extend({
      
      Obj: new Object(),
      fieldName: '',
      containerId: '',
      fieldItem: new Array(),
      //fieldId: 0,
      hiddenFields: '',
      showField: true,
      
      labelManager: 'Stránky', 
      labelNoItemsSelected: 'Není vybráno žádné zboží',  
      labelRemoveThisItem: 'Odebrat tuto položku',
      labelRemove: 'Odebrat',
      labelAddItem: 'Přidat zboží',
      labelOpenManager: 'Otevřít průzkumník zboží',
      labelItemLabel: 'Název',
      labelItemAmount: 'Množství'
      
    },settings);
		
		initialize();
		
    if(settings.showField){show();}
    else{remove();}
    
    function initialize()
      {
        $('#' + settings.fieldName + ' label input').unbind("click").click(function(){
          if($(this).attr("checked")){show();}
          else{remove();}
        });
        
        settings.container = $('#' + settings.containerId);
        settings.idList = settings.containerId + '_list';
        settings.idButton = settings.fieldName + '_buttonManager';
        settings.saveOneRow = (settings.fieldType == "structure") ? true : false;
      }
      
    function show()
      {
        settings.container.append('<a class="butt_text bt_shoplistmanager" id="' + settings.idButton + '" title="' + settings.labelOpenManager+ '" href="javascript: void(0);">'+settings.labelAddItem+'</a>');
        settings.container.append('<div class="block_shoplist" id="'+settings.idList+'"></div>');
        $('#'+settings.idButton).click(function(){showManager();});
        showList();
      }
    
    function getDisabledItems()
      {
        var arr = new Array();
        var i = 0;
        
        for (x in settings.fieldItem)
          {
            arr[i] = settings.fieldItem[x]["page_id"];
            i++;
          }
        return arr;
      }
    
    function showManager()
      {
        var disabled = getDisabledItems();
        
        ShowDialogWindow({
          windowID: 'dlg_manager', 
          title: settings.labelManager, 
          width: 800, 
          height: 500, 
          callin: function(win){
          
          shopListManager({
            con: win,
            disabledItem: disabled
          });
          
          }, 
          callback: function(win){
            win.find('.row_item').each(function(){
              
              if($(this).find('input:checkbox').attr("checked"))
                {
                  var record = new Array();
                  record["page_id"] = $(this).find("input:checkbox").attr("value");
                  record["label"] = $(this).find(".td_manager_name").html();
                  record["amount"] = 1;
                  returnItem(record);
                }
              });
              showList(); 
          }
          });
      }
    
    function remove()
      {
        settings.container.html('');
      }
    
    function showList()
      {
        var disabled = getDisabledItems();
        settings.hiddenFields = '';
        $("#" + settings.idList).html('');
        $("#" + settings.idList).append('\n<table cellspacing="0"></table>');
        $("#" + settings.idList + ' table').append('\n<tr><th>'+settings.labelItemLabel+'</th><th>'+settings.labelItemAmount+'</th><th>&nbsp;</th></tr>');
        if(arrayLength(settings.fieldItem))
          { 
            for(x in settings.fieldItem)
              {
                showRow(x);
              }
            //settings.hiddenFields+='<input class="input_hidden" type="hidden" name="' + settings.fieldName + '_order_id" value="' + settings.fieldId + '" />'; 
              
            $("#" + settings.idList).append(settings.hiddenFields);
          }
        else
          {
            $('#' + settings.idList + ' table').append('<tr><td class="td_empty_note"><strong class="empty_note">' + settings.labelNoItemsSelected + '</strong></td></tr>');
          }
      }
    
    function showRow(x)
      {
        id_blockItem = settings.fieldName + '_item_' + x;
        
        $("#" + settings.idList + ' table').append(
          '<tr id="' + id_blockItem + '">' +
          '<td class="td_shoplist_label">' + settings.fieldItem[x]["label"] + '</td>' + 
          '<td class="td_shoplist_amount"><input name="' + settings.fieldName + '_amount['+x+']" type="text" value="' + settings.fieldItem[x]["amount"] + '" /></td>' + 
          '<td class="td_shoplist_toolbar">' +
          '<a class="butt_small bs_remove" title="' + settings.labelRemoveThisItem + '" href="javascript:void(0);">' + settings.labelRemove + '</a>' +
          '</td>' + 
          '</tr>'
        ); 
        
        $('#' + id_blockItem + ' .bs_remove').click(function(){removeItem(x);});
            
        settings.hiddenFields += '<input class="input_hidden" type="hidden" name="' + settings.fieldName + '_page_id['+x+']" value="' + settings.fieldItem[x]["page_id"] + '" />';
      }
      
    function returnItem(record)
      {
        settings.fieldItem[settings.fieldItem.length] = record;
      }
      
    function removeItem(x)
      {
        delete settings.fieldItem[x];
        showList();
      }
    
  }

$(document).ready(function() {
  $(".f_structure").each(function(){
    fieldType_Structure({Obj: $(this), showField: !$(this).hasClass("field_disabled"), fieldName: $(this).attr("id"),fieldType: "structure",containerId: "container_"+$(this).attr("id"),fieldItem: Structure[$(this).attr("id")]});
  });
  $(".f_relations").each(function(){
    fieldType_Structure({Obj: $(this), showField: !$(this).hasClass("field_disabled"), fieldName: $(this).attr("id"),fieldType: "relations",containerId: "container_"+$(this).attr("id"),fieldItem: Structure[$(this).attr("id")]});
  });
}); 

var Structure = new Array();
var StructureField = new Array();

function fieldType_Structure(settings)
  {
    settings = jQuery.extend({
      
      Obj: new Object(),
      fieldName: '',
      fieldType: 'structure',
      containerId: '',
      fieldItem: new Array(),
      hiddenFields: '',
      showField: true,
      saveOneRow: false,
      
      labelManager: 'Stránky', 
      labelNoItemsSelected: 'Nejsou vybrána žádná zařazení',  
      labelRemoveThisItem: 'Odebrat toto zařazení',
      labelRemove: 'Odebrat',
      labelAddItem: 'Přidat zařazení',
      labelEditThisItem: 'Upravit toto zařazení',
      labelOpenManager: 'Otevřít průzkumník stránek'
      
    },settings);
		
		initialize();
		
    if(settings.showField){show();}
    else{remove();}
    
    function initialize()
      {
        $('#' + settings.fieldName + ' label input').unbind("click").click(function(){
          if($(this).attr("checked")){show();}
          else{remove();}
        });
        
        settings.container = $('#' + settings.containerId);
        settings.idList = settings.containerId + '_list';
        settings.idButton = settings.fieldName + '_buttonManager';
        settings.saveOneRow = (settings.fieldType == "structure") ? true : false;
      }
      
    function show()
      {
        settings.container.append('<a class="butt_text bt_structuremanager" id="' + settings.idButton + '" title="' + settings.labelOpenManager+ '" href="javascript: void(0);">'+settings.labelAddItem+'</a>');
        settings.container.append('<div class="block_structurelist" id="'+settings.idList+'"></div>');
        $('#'+settings.idButton).click(function(){showManager();});
        showList();
      }
    
    function getDisabledItems(key)
      {
        var arr = new Array();
        var i = 0;
        
        
        
        for (x in settings.fieldItem)
          {
            if(settings.fieldItem[x]["key"] != key) {arr[i] = settings.fieldItem[x]["key"];}
            i++;
          }
          
        if(settings.fieldItem.length && settings.fieldItem[0]["id"] != 0){arr[i] = settings.fieldItem[0]["id"];}
        //alert(arr.join(","));
        return arr;
      }
    
    function showManager(x)
      {
        var x = x || ''; 
        var selected = x.length ? settings.fieldItem[x]["key"] : '';
        var disabled = getDisabledItems((x.length ? settings.fieldItem[x]["key"] : ''));
        var disabled_section = settings.fieldItem.length && settings.fieldItem[0]["id"] != 0 ? [settings.fieldItem[0]["id"]] : new Array();
        var path = x.length ? settings.fieldItem[x]["path"] : [0,1];
        
        ShowDialogWindow({
          windowID: 'dlg_manager', 
          title: settings.labelManager, 
          width: 800, 
          height: 500, 
          callin: function(win){
          
          structureManager({
            con: win,
            selectedItem: selected,
            disabledItem: disabled,
            disabledSection: disabled_section,
            multiple: false,
            Path: path,
            type: "structure"
          });
          
          }, 
          callback: function(win){
            win.find('.item').each(function(){
              
              if($(this).find('input:checkbox').attr("checked"))
                {
                  var record = new Array();
                  if(!x.length){record["id"] = 0;}
                  else{record["id"] = settings.fieldItem[x]["id"];}
                  record["key"] = $(this).find("input:checkbox").attr("value");
                  record["path"] = $(this).find("input:checkbox").attr("path").split(",");
                  record["label"] = $(this).find("input:checkbox").attr("label");
                  returnItem(x, record);
                }
              });
              showList(); 
          }
          });
      }
    
    function remove()
      {
        settings.container.html('');
      }
    
    function showList()
      {
        var disabled = getDisabledItems();
        settings.hiddenFields = '';
        $("#" + settings.idList).html('');
        $("#" + settings.idList).append('\n<table cellspacing="0"></table>');
        if(arrayLength(settings.fieldItem))
          { 
            for(x in settings.fieldItem)
              {
                //if(!in_array(settings.fieldItem[x]["key"], disabled))
                //  {
                    showRow(x);
                //  }
                //else
                //  {
                //    showNotice(settings.Obj, 'Nepovolené zařazení stránky "'+settings.fieldItem[x]["label"]+'" bylo vyřazeno');
                //  }
              }
            $("#" + settings.idList).append(settings.hiddenFields);
          }
        else
          {
            $('#' + settings.idList + ' table').append('<tr><td class="td_empty_note"><strong class="empty_note">' + settings.labelNoItemsSelected + '</strong></td></tr>');
          }
      }
    
    function showRow(x)
      {
        id_blockItem = settings.fieldName + '_item_' + x;
        
        $("#" + settings.idList + ' table').append(
          '<tr id="' + id_blockItem + '">' +
          '<td class="td_structure_link"><a href="javascript:void(0);" title="' + settings.labelEditThisItem + '">' + settings.fieldItem[x]["label"] + '</a></td>' + 
          '<td class="td_structure_toolbar">' +
          (
            (settings.saveOneRow && arrayLength(settings.fieldItem)>1) || !settings.saveOneRow ?
             '<a class="butt_small bs_remove" title="' + settings.labelRemoveThisItem + '" href="javascript:void(0);">' + settings.labelRemove + '</a>'
             :
             '&nbsp;'
          ) +
          '</td>' + 
          //'<td class="td_empty_note"><strong class="empty_note">' + settings.labelNoItemsSelected + '</strong></td>' + 
          '</tr>'
        ); 
        
        $('#' + id_blockItem + ' .td_structure_link a').click(function(){showManager(x);});
        $('#' + id_blockItem + ' .bs_remove').click(function(){removeItem(x);});
            
        settings.hiddenFields += 
              '<input class="input_hidden" type="hidden" name="' + settings.fieldName + '_id['+x+']" value="' + settings.fieldItem[x]["id"] + '" />' + 
              '<input class="input_hidden" type="hidden" name="' + settings.fieldName + '_key['+x+']" value="' + settings.fieldItem[x]["key"] + '" />';
      }
      
    function returnItem(x, record)
      {
        settings.fieldItem[(x.length ? x : settings.fieldItem.length)] = record;
      }
      
    function removeItem(x)
      {
        delete settings.fieldItem[x];
        showList();
      }
    
  }


$(document).ready(function() {
  $(".field").each(function(){
    var obj = $(this);
    $(this).find("> label input").click(function(){
      obj.toggleClass("field_disabled");
      obj.removeClass("field_ok").removeClass("field_fail");
      obj.find(".ff input, .ff select, .ff textarea").attr("disabled", !$(this).attr("checked"));
      //obj.find(".ff input, .ff select, .ff textarea").attr("value", "");
    });
  });
}); 
