/**
 * Hlavni objekt globalnich funkci EdgeFrame CMS Fronendu
 */
if (typeof(console) == undefined) {
	console = {
			log: function() {}
	};
}
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 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="Warning!">'+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 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();
         },
         /**
          * 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);
        		 }
        	 });
         }
};

$(document).ready( function() {
	$("#map .more").click( function() {
		$('#support_sidebar').hide();
		$('#content').css({
					width :'785px', //465;
					margin :'0 0 0 15px'					
		});
		$('#content h1').css({
			'background-position' :'95% bottom'
		});
		var bigmapURL = $('#BigMap').text();
		if ( $('#detail').size() != 0 ) {
			$('#detail').after('<div id="detailmap"><a href="javascript:void(0)" class="close-map-detail">Zavřít detail mapy</a><iframe id="bigmapframe" name="bigmapframe" src="'+bigmapURL+'"></iframe></div>');
		} else {
			$('#text').after('<div id="detailmap"><a href="javascript:void(0)" class="close-map-detail">Zavřít detail mapy</a><iframe id="bigmapframe" name="bigmapframe" src="'+bigmapURL+'"></iframe></div>');
		}
		$.scrollTo($("#detailmap"), 800);
		$('.close-map-detail').unbind().click(function() {
			$.scrollTo($("#breadcrumbs_box"), { duration:800, offset: { left:0,top:-50} } );
			$('#detailmap').remove();
			$('#content').css({
						margin: '0 15px',						
						width: '465px'				
			});
			$('#content h1').css({
				'background-position' : '347px bottom'
			});
			$('#support_sidebar').show();			
		});	
	});
});

