
/****************** ano,ne dialog **************************/
jQuery.extend({
    yesNo: function($text, $title, $yesFunction, $noFunction, $params) {
		if($noFunction == undefined){
			$noFunction = function(){
				$dialog.destroy();
			};
		}
		if($yesFunction == undefined){
			$yesFunction = function(){
				$dialog.destroy();
			};
		}
	
		var $params = jQuery.extend({
			title: $title,
			icon: 'question',
			width: 350,
			minHeight: 100,
			buttons: {
				Ano: function(){
					$yesFunction($dialog);
				},
				Ne: function(){
					$noFunction($dialog);
				}
			}
		}, $params);
		
		var $dialog = jQuery.hmcDialog(
				$text, 
				$params
		);
	}
});

/****************** ajax **************************/
jQuery.extend({
    hmcAjax: function($url, $data, $params) {
		var $params = jQuery.extend({
			type: "POST",
			url: $url,
			data: $data,
            errorReturn: function($data){
				if(typeof $data == 'object'){
					jQuery.hmcDialog($data.text, {width: 400, minHeight: 100, icon: 'error', title: $data.titulek}, false);
				}else{
					jQuery.hmcDialog($data, {width: 400, minHeight: 100, icon: 'error'}, false);
				}
			},
			successReturn: function($return){
				
			},
			success: function($return){
				try{
                   eval('var $eval=' + $return);
                   if($eval.type == 'error'){
                       $params.errorReturn($eval.data);
                   }else{
                	   $params.successReturn($eval.data);
                   }
				}catch($e){
					$params.successReturn($return);
                }
            },
            error: function(XMLHttpRequest, textStatus, errorThrown){
            	$params.errorReturn(textStatus);
            }
		}, $params);
		jQuery.ajax($params);
	}
});

/****************** page in window **************************/
jQuery.extend({
	hmcWindowPage: function($url, $data, $dialogParams, $closePrevious) {
		var $this = jQuery.extend({}, this);
	
		var $dialog = jQuery.hmcDialog('<div class="loadingDiv"></div>', $dialogParams, $closePrevious);
		var $contentDiv = $dialog.getContentDiv();
		var $titleBar = $dialog.getTitleBar();
		var $title = $titleBar.children('.ui-dialog-title');
		var $paginationBar = jQuery('<div class="paginationBar"></div>');
		
		var $filterBar = jQuery('<div class="filterBar ui-corner-all"><div class="inner ui-widget-header">Žádný filtr není k dispozici</div></div>');
		var $reloadButton = jQuery('<a class="ui-dialog-titlebar-reload ui-corner-all" href="#"><span class="ui-icon"></span></a>');
		var $filterButton = jQuery('<a class="ui-dialog-titlebar-filter ui-corner-all" href="#"><span class="ui-icon"></span></a>');
		
		$contentDiv.after($paginationBar);
		$contentDiv.before($filterBar);
		$title.after($reloadButton);
		$title.after($filterButton);
		
		var $loadingDiv = jQuery('<div class="loadingDiv"></div>');
		$loadingDiv.insertBefore($contentDiv);
		
		$reloadButton.hover(function(){
			$reloadButton.addClass('ui-state-hover');
		},function(){
			$reloadButton.removeClass('ui-state-hover');
		});
		
		$reloadButton.click(function(event){
			event.preventDefault();
			$dialog.reload();
		});
		
		$dialog.addListener('beforeMinimalize', function($text){
			$filterButton.removeClass('visible');
			$filterBar.hide();
			$loadingDiv.hide();
			$paginationBar.hide();
		});
		
		$dialog.addListener('beforeMaximalize', function($text){
			$paginationBar.show();
		});
		
		$filterButton.hover(function(){
			$filterButton.addClass('ui-state-hover');
		},function(){
			$filterButton.removeClass('ui-state-hover');
		});
		
		$filterButton.click(function(event){
			$filterButton.toggleClass('visible');
			$filterBar.toggle();
			event.preventDefault();
		});	
		
		var $dialogId = $dialog.getId();
		var $data = jQuery.extend({
			dialogId: $dialogId
		}, $data);
		
		var $params = {
				data: $data,
				url: $url
		};
		
		jQuery.extend($dialog,{
            reload: function($html){
            	ajax($params.url, $params.data);
            },
            setUrl: function($url){
            	$params.url = $url;
            },
            setData: function($name, $value){
            	eval('$params.data.' + $name + '=$value');
            }
		});
		
		function ajax($url, $data, $first){
			$loadingDiv.width($contentDiv.hmcWidth());
			$loadingDiv.height($contentDiv.hmcHeight());
			$loadingDiv.show();
			jQuery.hmcAjax($url, $data, {
				successReturn: function($return){
					$contentDiv.html($return);
					$loadingDiv.hide();
					
					var $filter = $contentDiv.find(".filterForm");
					if($filter.html() != null){
						var $filterNamespace = $filter.find('input[name=filterNamespace]').val();
						$filter.find('input[name=filterNamespace]').remove();
						$filterBar.find('.inner').html($filter);
						$filter.submit(function(){
							var $data = {};
							jQuery(this).find(':input').each(function(){
								var $item = jQuery(this);
								if($filterNamespace == undefined || $filterNamespace == ''){
									$dialog.setData($item.attr('name'), $item.val());
								}else{
									eval('$data.' + $item.attr('name') + '=$item.val();');
								}
							});
							if($filterNamespace != undefined && $filterNamespace != ''){
								$dialog.setData($filterNamespace, $data);
							}
							$dialog.reload();
							return false;
						});
					}
					
					var $paginator = $contentDiv.find(".paginationControl");
					$paginationBar.html($paginator);
					$paginator.find('a').click(function($event){
						$event.preventDefault();
						$dialog.setUrl(jQuery(this).attr("href"));
						$dialog.reload();
					});
					
					$dialog.autoHeight();
					
					priraditJs($contentDiv);
				}
			});
		}
		
		ajax($url, $data, true);
		
		return $this;
	}
});
 
 /****************** dialog **************************/

jQuery.fn.hmcDialog = function() {
    return jQuery(this).data('dialog');
};

jQuery.extend({
    hmcDialog: function($text, $params, $closePrevious) {
		var HMC_DIALOG_DIV = 'hmcDialogDiv';
		
		$count = jQuery(document).data('HMC_DIALOG_DIV_COUNT');
		if($count == undefined){
			$count = 0;
		}
		$count++;
		jQuery(document).data('HMC_DIALOG_DIV_COUNT', $count);

		var $dialogName = HMC_DIALOG_DIV + $count;

		if($text == undefined){
			$text = '';
		}

		if($closePrevious == undefined){
			$closePrevious = true;
		}
		
		if($closePrevious){
			$previous = jQuery("div[rel='hmcDialogs']");
			$previous.each(function($i){
				jQuery(this).hmcDialog().destroy();
			});
		}

		if(typeof $text == 'object'){
			$text = $text.html();
		}

		var $params = jQuery.extend({
			bgiframe: false,
			resizable: false,
			modal: false,
			draggable: true,
			width: 900,
			minHeight: 450,
			close: function(){
				$dialog.destroy();
			},
			overlay: {
				backgroundColor: '#000',
				opacity: 0.5
			},
			listeners: new Array
		}, $params);

		if($params.icon != null){
	        $text = '<div class="icon ' + $params.icon + '">' + $text + '</div>';
	    }

		var $content = jQuery('<div style="display:none">' + $text + '</div>').dialog($params);
		var $dialog = $content.parent();
		var $titleBar = $dialog.children('.ui-dialog-titlebar');

		$dialog.data('dialog', $dialog);
		$dialog.attr('id', $dialogName);
		$dialog.attr('rel', 'hmcDialogs');
        
		jQuery.extend($dialog,{
			destroy: function(){
				$content.dialog('destroy');
				$content.remove();
			},
			getId: function(){
                return $dialogName;
            },
            getContentDiv: function(){
            	return $content;
            },
            getTitleBar: function(){
            	return $titleBar;
            },
            addListener: function($event, $function){
            	if(!jQuery.arrayKeyExist($event, $params.listeners)){
            		$params.listeners[$event] = new Array;
            	}
            	var $count = $params.listeners[$event].length;
            	$params.listeners[$event][$count] = $function;
            },
            getListeners: function($event){
            	var $return = new Array();
            	if(jQuery.arrayKeyExist($event, $params.listeners)){
            		$return  = $params.listeners[$event];
            	}
            	return $return;
            },
            autoHeight: function(){
            	$dialog.css('height', 'auto');
            },
            html: function($html){
            	return $dialog.getContentDiv().html($html);
            }
            
		});

		var $title = $titleBar.children('.ui-dialog-title');
		var $zmenseni = jQuery('<a class="ui-dialog-titlebar-collapsible ui-corner-all" href="#"></a>');
		var $zmenseniSpan = jQuery('<span class="ui-icon"></span>');
		
		$zmenseni.html($zmenseniSpan);
		$title.after($zmenseni);
		
		var $funkce = function(event){
			event.preventDefault();
			$dialog.autoHeight();
			if($dialog.hasClass('collapsed')){
				jQuery.forIn($dialog.getListeners('beforeMaximalize'), function($index, $value){
					$value();
				});
				$dialog.removeClass('collapsed');
			}else{
				jQuery.forIn($dialog.getListeners('beforeMinimalize'), function($index, $value){
					$value();
				});
				$dialog.addClass('collapsed');
			}
		};
			
		$titleBar.dblclick($funkce);
		$zmenseni.click($funkce);
		
		$zmenseni.hover(function(){
			$zmenseni.addClass('ui-state-hover');
		},function(){
			$zmenseni.removeClass('ui-state-hover');
		});
		
		return $dialog;
	}
});
/**************************************************/

/****************** status bar **************************/
jQuery.extend({
    statusBar: function ($classParams){
		var $this = jQuery.extend({}, this);

        var $classParams = jQuery.extend({
        	items: new Array(),
        	animationEffect: 'highlight',
        	animationDelay: 500,
        	hidden: true,
            defaultStatusBarPlace: '#main_statusbar',
            statusBar: null,
            defaultStatusBarHeadPlace: '#main_statusbar_header',
            statusBarHead: null,
            defaultStatusBarContentPermanentPlace: '#main_statusbar_content_permanent',
            statusBarContenPermanent: null,
            defaultStatusBarContentTemporaryPlace: '#main_statusbar_content_temporary',
            statusBarContentTemporary: null
		}, $classParams);
		
        $classParams.defaultStatusBar = jQuery($classParams.defaultStatusBarPlace);
        $classParams.defaultStatusBarHead = jQuery($classParams.defaultStatusBarHeadPlace);
        $classParams.statusBarContenPermanent = jQuery($classParams.defaultStatusBarContentPermanentPlace);
        $classParams.statusBarContentTemporary = jQuery($classParams.defaultStatusBarContentTemporaryPlace);
        
		jQuery.extend($this,{
			addItem: function($item){
				$item.addStatusBar($this);
				$classParams.items[$classParams.items.length] = $item;
				if($item.isPermanent()){
					$this.getStatusBarContentPermanent().append($item.render());
				}else{
					$this.getStatusBarContentTemporary().append($item.render());
				}
				render();
			},
			removeItem: function($removedItem){
				jQuery.forIn($this.getItems(),function($index, $item){
					if($removedItem == $item){
						delete $classParams.items[$index];
						render();
					}
				});
			},
			getItems: function($text){
				return $classParams.items;
			},
			getItemsCount: function($text){
				var $count = 0;
				jQuery.forIn($this.getItems(),function($index, $item){
					$count++;
				});
				return $count;
			},
			getStatusBar: function($text){
				return $classParams.defaultStatusBar;
			},
			getStatusBarHead: function($text){
				return $classParams.defaultStatusBarHead;
			},
			getStatusBarContentPermanent: function(){
				return $classParams.statusBarContenPermanent;
			},
			getStatusBarContentTemporary: function(){
				return $classParams.statusBarContentTemporary;
			}
		});
		
		function render()
		{ 
			if($this.getItemsCount() && $classParams.hidden){
				$classParams.hidden = false;
				$this.getStatusBar().show($classParams.animationEffect, {}, $classParams.animationDelay);
			}
		    if(!$this.getItemsCount() && !$classParams.hidden){
		    	$classParams.hidden = true;
				$this.getStatusBar().hide($classParams.animationEffect, {}, $classParams.animationDelay);
			}
		}
		
		return $this;
	},
	statusBarItem: function ($text, $itemParams){
		var $this = jQuery('<div></div>');
		
		var $itemParams = jQuery.extend({
	    	text: '',
	    	delay: 0,
	    	animationEffect: 'highlight',
	    	animationDelay: 500,
	    	statusBar: null,
	    	afterDelayFunction: function(){
				$this.remove();
			},
			timeout: null
		}, $itemParams);
		
		$itemParams.text = $text;
	
		jQuery.extend($this,{
			render: function(){
				var $removeButton = jQuery("<div class='floatLeft'>x</div><div class='cleaner'></div>");
				$removeButton.click(function(){
					$this.remove();
				});
				$this.append("<div class='floatLeft'>" + $itemParams.text + "</div>");
				$this.append($removeButton);
				return $this;
			},
			remove: function(){
				if($itemParams.timeout){
					clearTimeout($itemParams.timeout);
					$itemParams.timeout = null;
				}
				$this.hide($itemParams.animationEffect, {}, $itemParams.animationDelay);
				jQuery($this).remove();
				$this.getStatusBar().removeItem($this);
			},
			addStatusBar: function($statusBar){
				$itemParams.statusBar = $statusBar;
				if($itemParams.delay){
					$itemParams.timeout = setTimeout ($itemParams.afterDelayFunction, $itemParams.delay );
				}
			},
			getStatusBar: function(){
				return $itemParams.statusBar;
			},
			isPermanent: function(){
				return $itemParams.delay == 0 ? true : false;
			}
		});
		return $this;
	}

});
/********************************************/

/****************** progress bar **************************/
jQuery.fn.hmcProgressbar = function($params, $index, $value) {
	var $this = jQuery(this);

	if($this.length > 1){
		alert('Vytvářejte progressbary po jednom');
		return null;
	};

	var $new = false;
	if($this.data('progressbar') == undefined){
		$new = true;
	}else{
		$this = $this.data('object');
	}

	function render()
	{
		setValue($params);
		if($params.showText){
			$text.html($params.renderText($params));
			$text.attr('style', 'top:-' + Math.round((($this.height() - $text.height()) / 2) + $text.height()) + 'px');
		}
	}

	function setValue($params)
	{
		if($params.maxValue - $params.minValue == 0){
			$value = 0;
		}else{
			//$value = Math.round((($params.value - $params.minValue) / ($params.maxValue - $params.minValue)) * 100);
			$value = (($params.value - $params.minValue) / ($params.maxValue - $params.minValue) * 100);
		}
		$this.progressbar('option', 'value', $value);
	}

	if($new){
		var $params = jQuery.extend({
			maxValue: 100,
			minValue: 0,
			value: 0,
			stepValue: 0,
			showText: true,
			renderText: function($item){
				return jQuery.numberFormat($item.value, 0, null, ' ', 'floor') + '/' + jQuery.numberFormat($item.maxValue, 0, null, ' ');
			}
		}, $params);

		var $item = $this.progressbar();
		if($params.showText){
			var $text = jQuery('<div class="ui-progressbar-textvalue">');
			$item.append($text);
		}
		render();

		jQuery.extend($this,{
			setRatio: function($value){
			    if($value > 1){
			    	$params.value = $params.maxValue * ($value / 100);
			    }else if($value < 1 && $value > 0){
			    	$params.value = $params.maxValue * $value;
			    }else if($value == 0){
			    	$params.value = 0;
			    }
				render();
			},
			setValue: function($value){
        		$params.value = $value;
				render();
			},
			getValue: function(){
        		return $params.value;
			},
			setStep: function($value){
				if($params.stepValue != null){
					if($params.stepValue > 0){
						$params.value = ($value * $params.stepValue) + $params.minValue;
					}else{
						$params.value = $params.maxValue + ($value * $params.stepValue);
					}
     			render();
				}else{
					$this.setRatio($value);
				}
			},
			setMaxValue: function($value){
				$params.maxValue = $value;
				render();
			},
			setMinValue: function($value){
				$params.minValue = $value;
				render();
			}
		});
		$this.data('object', $this);
	}
	return $this;
};


/**************************************************/

/****************** dalsi uzitecne funkce **************************/
jQuery.extend({
	arrayKeyExist: function ($key, $array){
		return (typeof $array[$key] != 'undefined');
	},
	forIn: function ($array, $function){
		for($index in $array){
			if($index != 'remove'){
				$function($index, $array[$index]);
			}
		}
	},
	numberFormat: function ($number, $decimals, $dec_point, $thousands_sep, $roundType){
	    if($dec_point == undefined || $dec_point == null){
	        $dec_point = '.';
        }
	    if($thousands_sep == undefined || $thousands_sep == null){
	        $thousands_sep = ' ';
        }
	    if($roundType == undefined || $roundType == null){
	        $roundType = 'round';
        }
        if($decimals != undefined && $decimals != null){
            if(typeof $number == 'string'){
            	$number = parseFloat($number);
            }
            if($roundType == 'round'){
                $number = Math.round($number);
            }else if($roundType == 'ceil'){
                $number = Math.ceil($number);
            }else if($roundType == 'floor'){
                $number = Math.floor($number);
            }
        }

        $number += '';
        var $x = $number.split('.');
        $number = $x[0];
        var $dec = $x[1];

        if($thousands_sep != ''){
	        var $i = 0;
	        var rgx = /(\d+)(\d{3})/;
	        while (rgx.test($number)) {
	        	$number = $number.replace(rgx, '$1' + $thousands_sep + '$2');
	        	if($i++ > 5){
	        	    break;
	            }
	        }
        }
        if($dec != undefined){
            $number = $number + $dec_point + $dec;
        }
		return $number;
	}
});

/****************** rozmery **************************/
jQuery.fn.hmcTop = function() {
    var $this = jQuery(this);
    var $top = $this.position().top;
	var $marginTop = parseInt($this.css('margin-top').replace('px', ''));
	return $top + $marginTop;
};

jQuery.fn.hmcLeft = function() {
	var $this = jQuery(this);
	var $left = $this.position().left;
	var $marginLeft = parseInt($this.css('margin-left').replace('px', ''));
	return $left + $marginLeft;
};

jQuery.fn.hmcHeight = function() {
	var $this = jQuery(this);
	var $height = $this.height();
	var $paddingTop = parseInt($this.css('padding-top').replace('px', ''));
	var $paddingBottom = parseInt($this.css('padding-bottom').replace('px', ''));
	return $height + $paddingTop + $paddingBottom;
};

jQuery.fn.hmcWidth = function() {
	var $this = jQuery(this);
	var $width = $this.width();
	var $paddingLeft = parseInt($this.css('padding-left').replace('px', ''));
	var $paddingRight = parseInt($this.css('padding-right').replace('px', ''));
	return $width + $paddingLeft + $paddingRight;
};
