/**
 * Hlavni objekt globalnich funkci EdgeFrame CMS Fronendu
 */

/* Copyright (c) 2009 Michael Manning (actingthemaggot.com) Dual licensed under the MIT (MIT-LICENSE.txt) and GPL (GPL-LICENSE.txt) licenses.*/
(function(A){A.fn.extend({currency:function(B){var C={s:",",d:".",c:2};C=A.extend({},C,B);return this.each(function(){var D=(C.n||A(this).text());D=(typeof D==="number")?D:((/\./.test(D))?parseFloat(D):parseInt(D)),s=D<0?"-":"",i=parseInt(D=Math.abs(+D||0).toFixed(C.c))+"",j=(j=i.length)>3?j%3:0;A(this).text(s+(j?i.substr(0,j)+C.s:"")+i.substr(j).replace(/(\d{3})(?=\d)/g,"$1"+C.s)+(C.c?C.d+Math.abs(D-i).toFixed(C.c).slice(2):""));return this})}})})(jQuery);jQuery.currency=function(){var A=jQuery("<span>").text(arguments[0]).currency(arguments[1]);return A.text()};

EFF = {			
		/**
		 *  Funkce ukazuje u elementu ajaxovy preloader (cekejte prosim)
		 */		
		ajaxLoader: function (element, state) {					
			switch (state) {
			case 'show' :				
				$(element).before('<div class="ajax-loader">čekejte prosím...</div>');
				break;
			default :				 
				$(element).prev('div.ajax-loader').remove();		
			}
		},
		 /**
         * Funkce zobrazi kratkou zpravu
         */
        uiAjaxBlock: function( container ) {
            $( container ).block({
 	   			message: 'odesílám požadavek...',
 	   			css: { 
 	   	            border: 'none', 
 	   	            padding: '0px', 
 	   	            width: 'auto',
 	   	            backgroundColor: 'none', 		   	            
 	   	            opacity: 1, 
 	   	            color: '#ccc' 
 	   	        },
 	   	        overlayCSS:  { 
 	   	        	backgroundColor: '#000', 
 	   	        	opacity:         0.8 
 	   	        }
 	   		});                  
         },  
         uiAjaxUnBlock: function( container ) {
        	 $( 'div:last', container ).filter('.blockUI').html('požadavek odeslán...');
        	 $( container ).unblock();
         },
		/**
		 *  Funkce vyparsuje ID z retezce
		 */ 
		getID: function (str, pos, delimiter ) {            
            var strArray = str.split( delimiter );
            if (strArray.length < pos) {
                alert("Chyba: Nemohu načíst ID");
                return false;
            } else {
                return strArray[pos];
            }
        },
        /**
         *  Funkce zobrazi Chybovou hlášku
         */
        uiAlert: function (message, options) {
        		if (typeof(options) == 'undefined') var options = {};
            	$("body").append('<div id="uiAlert" title="Pozor!">'+message+'</div>');
            	 $("#uiAlert").dialog({             		
            		resizable	: true,
            		modal		: true,
            		width		: 380,
        		    overlay	  : { 
        		        opacity: 0.5, 
        		        background: "black" 
        		    },
        		    buttons	  : { 
        		        "Ok": function() {                  		    		
        		    		$(this).dialog("close");
        		        }         		    
        		    },
        		    close : function(e,ui) {        
	        		    	if (typeof(options.close) == 'function') {
	    		    			options.close();
	    		    		}
            		    	$(this).remove();            		 
        		    }
            	 });
            	/* $(".ui-dialog-titlebar-close").removeClass("ui-state-focus");
         		 $(".ui-dialog").focus();*/
        },
        /**
         * Funkce zobrazi kratkou zpravu
         */
        uiInfo: function( message, delay, options ) {    
        	var opts = { 
        				close: null
        	};
        	$.extend( opts, options );
            if (typeof (delay) != 'number')  delay = 700;            
            $.blockUI({
 	   			message: '<div class="ui-dialog ui-widget ui-widget-content ui-corner-all"><br/>'+ message +'<br/>&nbsp;</div>',
 	   			css: { 
 	   	            border: 'none', 
 	   	            padding: '0px', 
 	   	            backgroundColor: 'none', 		   	            
 	   	            opacity: 1, 	   	            
 	   	            color: '#fff' 
 	   	        },
 	   	        overlayCSS:  { 
 	   	        	backgroundColor: '#000', 
 	   	        	opacity:         0.8 
 	   	        } 
 	   		});                  
            if ( typeof( opts.close ) == 'function' ) {
            	setTimeout( opts.close , delay);
            }
            setTimeout($.unblockUI, delay);       
         },        
        /**
         * Funkce zobrazi zprávu (dialogovy okno)
         * TODO: dodelat Timeout (automaticky zavreni za X vterin) 
         */
        uiMessage: function (message, options) {        	
        	if (typeof(options) == 'undefined') var options = {};
        	if (typeof(options.title) == 'undefined') options.title = 'Zpráva';
        	if (typeof(options.timeout) != 'undefined') var timeout = true; else var timeout = false;
        	var defaultDialogOptions = {        			
                		resizable	: true,
                		modal		: true,        		
                		overlay	  	: { 
				                		opacity: 0.5, 
				                		background: "black" 
			                		  },                	       		                   	
	                	close : function(e,ui) {        
	                		if (typeof(options.close) == 'function') {
	                			options.close();
	                		}
	                		$(this).remove();            		 
	                	}
        	}
        	if (timeout) {        		        	
        		var dialogOptions = {
        			buttons	  : { 
	    				"Ok": function() {                  		    		
	        					$(this).dialog("close");
	        				}  
					}
        		}
        	} else {
        		var dialogOptions = {
        			buttons	  : { 
	            				"Ok": function() {                  		    		
		            					$(this).dialog("close");
		            				}  
        						}
        		}
        	}
        	$("body").append('<div id="uiMessage" title="'+options.title+'">'+message+'</div>');     
        	$.extend(defaultDialogOptions, dialogOptions);
        	$("#uiMessage").dialog(defaultDialogOptions);
        	if (timeout == false) {
	        	$(".ui-dialog-titlebar-close").removeClass("ui-state-focus");
	        	$(".ui-dialog").focus();
        	}
        },
        /**
         *  Funkce ukáže dotazovací okno
         */
        uiConfirm: function(text, options) {
        	var defaultOptions = {
        		title: 'Dotaz:',
        		Ok	: "",
        		Cancel	: "",
        		resizable	: true,
        		modal		: true
        	}
        	
        	options = $.extend( defaultOptions, options);        	
        	$("body").append('<div id="uiConfirm"  title="'+options.title+'">'+text+'</div>');
        	 $("#uiConfirm").dialog({
        		resizable : options.resizable,
        		modal	  : options.modal,  
        		width	  : options.width,
        	 	height	  : options.height,
    		    overlay	  : { 
    		        opacity: 0.5, 
    		        background: "black" 
    		    },
    		    buttons	  : { 
    		        "Ok": function() {     		    		
    		    		if (typeof (options.Ok) == "function") {
    		    			options.Ok();
    		    		} else {
    		    			$(this).dialog("close");
    		    		}    		    		
    		        }, 
    		        "Zavřít": function() {    		        	
    		            if (typeof (options.Cancel) == "function") {
    		            	options.Cancel();
    		    		} else {
    		    			$(this).dialog("close");
    		    		}
    		        } 
    		    },
    		    close : function(e,ui) {        		   
    		    	$(this).remove();            		 
    		    },
    		    open : function(e, ui) {
    		    	 if (typeof (options.open) == "function") {
 		            	options.open();
 		    		} 
    		    }
        	 });
        	 $(".ui-dialog-titlebar-close").removeClass("ui-state-focus");
     		 $(".ui-dialog").focus();
         },
         URLEncoder : function( clearString ) {
        		  var output = '';
        		  var x = 0;
        		  clearString = clearString.toString();
        		  var regex = /(^[a-zA-Z0-9_.]*)/;
        		  while (x < clearString.length) {
        		    var match = regex.exec(clearString.substr(x));
        		    if (match != null && match.length > 1 && match[1] != '') {
        		    	output += match[1];
        		      x += match[1].length;
        		    } else {
        		      if (clearString[x] == ' ')
        		        output += '+';
        		      else {
        		        var charCode = clearString.charCodeAt(x);
        		        var hexVal = charCode.toString(16);
        		        output += '%' + ( hexVal.length < 2 ? '0' : '' ) + hexVal.toUpperCase();
        		      }
        		      x++;
        		    }
        		  }
        		  return output;
         },
         /**
          * Funkce zobrazi dialog oprávnění 
          */         
         uiPermissions: function( moduleID, itemID, regLang, multiLang ) {
        	 	
        	 	var uiPermFunc = {
        	 			/**
        	 			 * Nahrani prostredi dialogu
        	 			 */
        	 			open: function(customRegLang) {
        	 				if (multiLang == true) var showLang = true; else var showLang = false;        	 				
	        	 			EF.ajaxLoader("#uiPermissions","show");                  
		                	$.ajax({
		                		url: '/admin/modules/system/systemPermissions.ajax.php?sign='+moduleID+'-'+itemID+'-'+customRegLang+'&ev=app&ac=list&mod='+moduleID+'&ite='+itemID+'&sln='+showLang,
		                		dataType: "json",
		                		error: function(xhr, msg) {
			                		EF.uiAlert("Při načítání dat došlo k chybě.");                    
			                		EF.ajaxLoader("#uiPermissions","hide");
			                	},
			                	success: function(data) {
			                		EF.ajaxLoader("#uiPermissions","hide");
			                		if (data.status == "ok") {      
			                			$("#uiPermissions").html(data.content);	
			                			uiPermFunc.events();
			                		} else {                               			                			
			                			EF.uiAlert("Při načítání dat došlo k chybě!<br/>"+data.content);			                			
			                		}                        
			                	}                                               
		                	});
        	 			},
        	 			/**
        	 			 * Prirazeni eventu formulare
        	 			 */
        	 			events: function() {
        	 				//odstraneni radku
        	 				$("#uiPermissions .line-drop").unbind().click(function(){
        	 					if ($("#uiPermTable input[class^='selectHorizontal']").size() == 1) {
        	 						$("#uiPermTable input[class^='selectVertical']").hide();
        	 					}
        	 					$(this).parent().parent().remove();        	 					
        	 				});
        	 				//pridani radku
        	 				$("#uiPermissions .line-add").unbind().click(function() {
        	 					uiPermFunc.addPerm($(this));
        	 				});
        	 				//vyber jazyka
        	 				$("#uiPermissionsLang").unbind().change(function() {
        	 					var customRegLang = $(this).val()+regLang.substr(2,3);
        	 					uiPermFunc.open(customRegLang);
        	 				});        	 				        	 				
        	 				//oznaceni radku
        	 				$("#uiPermissions input[class^='selectHorizontal']").unbind().click(function(){ 
        	 					var line = $(this).attr("class");
        	 					line = line.replace('selectHorizontal','rule');        	 					
        	 					if ($(this).is(':checked')) {
        	 						$("#uiPermissions input[name^='"+line+"']").attr("checked","checked").each(function(i,e) {
        	 							uiPermFunc.checkSelectedInput(this);
        	 						});        	 						
        	 					} else {
        	 						$("#uiPermissions input[name^='"+line+"']").removeAttr("checked").each(function(i,e) {
        	 							uiPermFunc.checkSelectedInput(this);
        	 						});        	 						       	 						
        	 					}
        	 				});
        	 				//oznaceni sloupce
        	 				$("#uiPermissions input[class^='selectVertical']").unbind().click(function(){ 
        	 					var row = $(this).attr("class");
        	 					row = row.replace('selectVertical','');        	 					
        	 					if ($(this).is(':checked')) {
        	 						$("#uiPermissions input[name$='"+row+"']").attr("checked","checked").each(function(i,e) {
        	 							uiPermFunc.checkSelectedInput(this);
        	 						});        	 						        	 						
        	 					} else {
        	 						$("#uiPermissions input[name$='"+row+"']").removeAttr("checked").each(function(i,e) {
        	 							uiPermFunc.checkSelectedInput(this);
        	 						});        	 						       	 						
        	 					}
        	 				});
        	 				//hlidani oznaceni sloupce a radku po kliknuti na input
        	 				$("#uiPermissions input[name^='rule']").unbind().click(function(){ 
        	 					uiPermFunc.checkSelectedInput(this);        	 					        	 				
        	 				});
        	 			},
        	 			/**
        	 			 * Pridava novy radek s opravenim
        	 			 */
        	 			addPerm: function(e) {
        	 				var type = 'user';
        	 				if (e.is('.add-group')) {
        	 					type = 'group';
        	 				}
        	 				EF.ajaxLoader("#uiPermissions","show");                  
		                	$.ajax({
		                		url: '/admin/modules/system/systemPermissions.ajax.php?sign='+moduleID+'-'+itemID+'-'+regLang+'&ev=app&ac=add&tp='+type,
		                		dataType: "json",
		                		error: function(xhr, msg) {
			                		EF.uiAlert("Při načítání dat došlo k chybě.");                    
			                		EF.ajaxLoader("#uiPermissions","hide");
			                	},
			                	success: function(data) {
			                		EF.ajaxLoader("#uiPermissions","hide");
			                		if (data.status == "ok") {      
			                			$("#uiPermTable tbody").append(data.content);			                			
			                			$("#uiPermTable select.add-perm").unbind().change(function(){
			                				 uiPermFunc.addPermCheck($(this));	
			                			});
			                			
			                			uiPermFunc.events();
			                		} else {                               			                			
			                			EF.uiAlert("Při načítání dat došlo k chybě!<br/>"+data.content);			                			
			                		}                        
			                	}                                               
		                	});        	 				
        	 			},
        	 			/**
        	 			 * Hlida pridani noveho radku s opravnenim => nelze vkladat duplicity
        	 			 */
        	 			addPermCheck: function(e) {
        	 				var type = 'user';
        	 				if (e.is('.add-group')) {
        	 					type = 'group';
        	 				}
        	 				var id = e.val();
        	 				var chk = 'rule_';
        	 				var selHr = '';
        	 				if (type == 'group') {
        	 					chk = chk+id+'_0';
        	 					selHr = id+'_0';
        	 				} else {
        	 					chk = chk+'0_'+id;
        	 					selHr = '0_'+id;
        	 				}
        	 				if ($("#"+chk+'_r').size() == 1) {
        	 						EF.uiAlert("Toto oprávnění bylo nalezeno v seznamu, proto jej nelze přidat.",{close: function () {  e.parent().parent().remove(); }});        	 					
        	 						return false;
        	 				}
        	 				var tr = e.parent().parent();        	 				
    	 					$("input[class^='replace-']", tr).each(function(i,e) {
    	 							var newId = $(e).attr("class");
    	 							newId = chk+"_"+newId.substr(8,1);
    	 							$(e).attr("id",newId).removeAttr("class").attr("name",newId);     	 							
    	 					});
    	 					$("input[class='selectHorizontal-all']",tr).attr("class",'selectHorizontal_'+selHr);
        	 				var td = e.parent();
        	 				var name = $(':selected',e).text();
        	 				if (type != 'group') {
        	 					var i = name.indexOf('-');
        	 					name = '<span title="'+name.substr(i+1)+'">'+name.substr(0,i)+'</span>';
        	 				}
        	 				td.html(name); 
        	 				$("#uiPermTable input[class^='selectVertical']").show();
        	 				
        	 				$("input[name^='rule']",tr).each(function (i,e) {
        	 					uiPermFunc.checkSelectedInput(this);
        	 				});
        	 				uiPermFunc.events();
        	 			},
        	 			/**
        	 			 * hlida oznaceni radku a sloupce od elementu e
        	 			 */
        	 			checkSelectedInput: function(e) {
        	 				var rule = $(e).attr("name");        	 					
    	 					var row = rule.substr(-1,1);
    	 					var line = rule.substr(0, rule.length-2 );        	 					        	 					
    	 					var rows = true;
    	 					//console.log(rule);console.log(row);console.log(line);    	 					
    	 					$("#uiPermissions input[name$='"+row+"']").each(function(){
    	 						if (!$(this).is(':checked')) {
    	 							rows = false;
    	 						}
    	 					});
    	 					//console.log(rows);
    	 					var lines = true;
    	 					$("#uiPermissions input[name^='"+line+"']").each(function(){
    	 						if (!$(this).is(':checked')) {
    	 							lines = false;
    	 						}
    	 					});        	 		
    	 					//console.log(lines);
    	 					var endLine = line.replace('rule','selectHorizontal');
    	 					var endRow = 'selectVertical_'+row;
    	 					if (lines) {        	 						
    	 						$("#uiPermissions ."+endLine).attr("checked","checked");
    	 					} else {
    	 						$("#uiPermissions ."+endLine).removeAttr("checked");
    	 					}
    	 					if (rows) {        	 						
    	 						$("#uiPermissions ."+endRow).attr("checked","checked");
    	 					} else {
    	 						$("#uiPermissions ."+endRow).removeAttr("checked");
    	 					}
        	 			},
        	 			/**
        	 			 * Funkce ukládá výsledky
        	 			 */
        	 			save: function(close) {        	 			
        	 				var data = 'cr='+$("#uiPermissions #cr").val();
        	 				data = data +'&cl='+$("#uiPermissions #cl").val();
        	 				data = data +'&mo='+$("#uiPermissions #mo").val();
        	 				data = data +'&it='+$("#uiPermissions #it").val();
        	 				$("#uiPermissions input[name^='rule_']").each(function(i,e) {
        	 					var name = $(e).attr("name");
        	 					var state = $(e).is(':checked') ?  true : false;
        	 					data = data + '&'+name+'='+state;
        	 				});
        	 				//console.log(data);
        	 				$.ajax({
		                		url: '/admin/modules/system/systemPermissions.ajax.php?sign='+moduleID+'-'+itemID+'-'+regLang+'&ev=app&ac=save',
		                		dataType: "json",
		                		type: 'post',
		                		data: data,
		                		error: function(xhr, msg) {
			                		EF.uiAlert("Při ukládání dat došlo k chybě.");                    
			                		EF.ajaxLoader("#uiPermissions","hide");
			                	},
			                	success: function(data) {
			                		EF.ajaxLoader("#uiPermissions","hide");
			                		if (data.status == "ok") {      			                			
			                			EF.uiMessage("Oprávnění bylo úspěšne uloženo.",{close:close});			                			
			                		} else {                               			                			
			                			EF.uiAlert("Při ukládání dat došlo k chybě!<br/>"+data.content);			                			
			                		}                        
			                	}                                               
		                	});         	 				
        	 			},
        	 			checkBeforeSubmit: function() {
        	 				if ($("#uiPermissions").prev().is(".ajax-loader")) {
        	 						EF.uiMessage("Načítám oprávnění, počkejte prosím.");
        	 					return false;
        	 				} 
        	 				return true;
        	 			}
        	 			
        	 			
        	 	}
        	 	
             	$("body").append('<div id="uiPermissions"  title="Oprávnění CMS EdgeFrame"></div>');
             	 $("#uiPermissions").dialog({
             		resizable	: true,
             		modal		: true,
             		width	  : 470,             	 	
         		    overlay	  : { 
         		        opacity: 0.5, 
         		        background: "black" 
         		    },
         		    buttons	  : {
         		    	 "Zavřít": function() {     		            
      		           			$(this).dialog('close');
     		        	},
     		        	"Ok": function() {
            	 			if (uiPermFunc.checkBeforeSubmit()){
            	 				uiPermFunc.save(function(){$("#uiPermissions").dialog('close');});
            	 			}
         		    		
         		        },
         		    	"Použít": function() {
         		        	if (uiPermFunc.checkBeforeSubmit()){
         		        		uiPermFunc.save();
         		        	}
     		    		
     		        	},
     		        	"Obnovit": function() { 
     		        		uiPermFunc.open(regLang);
     		        	} 
         		       
         		    },
         		    close : function(e,ui) {        		   
         		    	$(this).remove();            		 
         		    },
         		    open : function(e, ui) {
         		    	uiPermFunc.open(regLang);
         		    }
             	 });
             	 $(".ui-dialog-titlebar-close").removeClass("ui-state-focus");
          		 $(".ui-dialog").focus();
         },
         /**
          * Funkce doplni do formulare (form) data (data)
          */
         fillForm: function( form,data) {        	 
        	 $.each(data, function(i, val) {
        		 var e = $("#"+i, form);        		         		 
        		 if (e.is(":checkbox")) {
        			 if (val) { e.attr("checked","checked"); } else { e.removeAttr("checked"); } 
        		 } else {
        			 e.val(val);
        		 }
        	 });
         },
         currency: function ( value )  {        	 
        	 return $.currency( value, {s:" ",d:",",c:2} ) + ' Kč';
		 }		   
};


$(document).ready( function() {

});

