var calbackSaveFunction = '';
$(function() { //
	// wait fce, source: http://docs.jquery.com/Cookbook/wait
    $.fn.wait = function(time, type) {
        type = type || "fx";
        time = time || 1;
        return this.queue(type, function() {
            var self = this;
            setTimeout(function() {
                $(self).dequeue();
            }, time);
        });
    };
    // posun po inputech v tabulce predpoklad je tedy cesta: <table><tr><td><input 
    $.fn.tableInputFocus = function( typ ){
    	var aktObj = this;
    	
    	if( $(aktObj).attr('class').match(/changeOn/g)  ){
    		$(aktObj).change();
    	}
		var stop = false;
		var nalezeno = false;
		var index = 0;
    	// hledani najblizsiho TR ( .parent('tr') mi nejak nefungoval... ) 
		var obj = $(this).parent();
		while( obj[0].nodeName != 'TR' &&  obj[0].nodeName != 'tr' ){
			obj = $(obj).parent();
		}
		switch( typ ){
			case 'left':
				break;
			case 'right':
				break;
		}
		
		var sadaTagu = 'input:not(:disabled)';
		var x = 0;
		var ok = false;
		// zjisteni aktualniho indexu pozice
		switch( typ ){
			case 'left':
				ok = false;
				break;
			case 'right':
				ok = false;
				break;
			default:
				ok = true;
				break;
		}
		$( 'td', $(obj)).each(function(){
			$( sadaTagu, $(this)).each(function(){
				if( ! stop ){
					if( $(this).attr('type') == 'text' ){
						if( $(this).attr('name') == $(aktObj).attr('name')  ){
							stop = true;
						}else{
							index++;
						}
					}
				}
			});
		});
		switch( typ ){
    		case 'left':
    			index--;
    			if( index < 0 ) index = 0;
    			break;
    		case 'right':
    			index++;
    			break;
    		case 'up':
    			// posun o radek nahoru
    			if( this[0].nodeName != 'SELECT'){
	    			obj = $(obj).prev('tr');
	    			while( $(sadaTagu,$(obj)).size() < index && $(obj).size() > 0 ){
	        			obj = $(obj).prev('tr');
	    			}
    			}
    			break;
    		case 'down':
    			// posun o radek dolu
    			if( this[0].nodeName != 'SELECT'){
	    			obj = $(obj).next('tr');
	    			while( $(sadaTagu,$(obj)).size() < index && $(obj).size() > 0 ){
	        			obj = $(obj).next('tr');
	    			}
    			}
    			break;
    	}
		// vyber spravneho inputu
		x = 0;
		aktObj = false;
		$( 'td', $(obj)).each(function(){
			var lastObj = false;
			$(sadaTagu,$(this)).each(function(){
				if( $(this).attr('type')  == 'text'){
    				if( x == index ){
    					aktObj = this;
    				}
    				x++;
				}
			});
		});
	    // provedeni focusu
		if( aktObj ){
			$(aktObj).focus();
		}
    }
    
    // zruseni docasnych elementu 
	$('.zmiz')
		.wait(2000)
		.hide(1000, function () {
		$(this).remove();
	});
	// HELP TEXT
	$('.help').live('click',function(){
		var id = $(this).attr('id');
		if( $('#'+id+'Text').size() > 0 ){
			var url = "#TB_inline?height=350&width=450&inlineId="+id+"Text&modal=false";
			tb_show("", url);
		}
	});
	$('.helpText').hide();
    
	// FORMS save
	$('.sendNastaveni').live('click', function(){ 
		var inputs = new Object;
		var parentId =  this.parentNode;
		$(this).blur();
		// fckeditor zkopirovat data do textareny
		FCKPrepareSave();
		var getData = '';
		var jeToLayout = false;
		switch( parentId.id ){
			case 'fragment-sklad':
				getData = GetDataSkladu();
				getData +='&saveTyp=sklad&pozice=admin';
				$('#skladData .changedRow').removeClass('changedRow');
				break;
			case 'fragment-objednavky':
				getData = GetDataObjednavky();
				getData +='&saveTyp=objednavky&pozice=admin';
				$('#objednavky .changedRow').removeClass('changedRow');
				break;
			default:
				$(':input', parentId ).each(function() {
					if (this.name != "") {  // ignorace inputu bez name
						if ((this.type == "radio" || this.type == "checkbox") && !this.checked) {
							// ignorovat nezaskrtle polozky
						} else {
							inputs[this.name] = this.value;
							getData += '&'+this.name+'='+encodeURIComponent(this.value);
						}
						if( this.name == 'saveTyp' && this.value == 'layout'){
							jeToLayout = true;
						}
					}
				});
				break;
		}
		if( jeToLayout ){
			getData +='&'+SendLayout();
		}
		//alert(zacatekUrl+'xmlgate.php?'+getData);
		// odeslani dat ke zpracovani
 		$.ajax({
			url:  zacatekUrl+'xmlgate.php',
			type: 'post',
			cache: false,
			data: getData,
		    dataType: 'xml',
		    timeout: 29000,
		    beforeSend:  function(){ mdAjaxFormBefore(parentId); },
		    error: function(){ mdAjaxFormError(parentId); },
		    success:  function(xml){ mdAjaxFormSuccess(parentId,xml); }
		});
		
	});
	// zavreni thickboxu
	$('.tbClose').live('click', function(){
		tb_remove();	
	});

	// odeslani dat layoutu
	function SendLayout(){
		var data = {};
		var getStr = '';
		var id = $(this).attr('id');
		var index = 0;         
		// levy sloupec
		$('#MDLayout .column').each(function(){
			id = $(this).attr('id');
			index = 0;         
			data[id] = {};
			$('.portlet',$(this)).each(function(){
				data[id][index] = $(this).attr('id');
				if( getStr != '') getStr +='&';
				getStr +='data['+id+']['+index+']='+$(this).attr('id');
				index++;	
			});
		});
		return getStr;
	};
	$('.ch').live('change', function(){ 
		$(this).change(function(){
			var obj = $(this).parent();
			while( obj[0].nodeName != 'TR' &&  obj[0].nodeName != 'tr' ){
				obj = $(obj).parent();
				if( $(obj).size() == 0 ) break;
			}
			$(obj).addClass('changedRow');
		});
	});
	$('.chBt').live('click', function(){ 
		$(this).click(function(){
			var obj = $(this).parent();
			while( obj[0].nodeName != 'TR' &&  obj[0].nodeName != 'tr' ){
				obj = $(obj).parent();
				if( $(obj).size() == 0 ) break;
			}
			$(obj).addClass('changedRow');
		});
	});
	
});
function GetDataFromBlock(blockname){
	var output = '';
	$(blockname).each(function (){
		$('input,select,textarea',$(this)).each( function(){
			if( this.value != '' && this.name != '' ){
				if( this.type == 'checkbox' || this.type == 'radio'){
					if( this.checked ){
						if( output != '') output += '&';
						output += this.name+'='+this.value;
					}
				}else{
					if( output != '') output += '&';
					output += this.name+'='+this.value;
				}
			}
		});
	});
	return output;
}



function msgClose( cas ){
	$('.load').fadeOut(cas);
}
// nastaveni a zobrazeni load divu pro prekryti aktivniho divu
function SetZobrazeni( pozice, showDiv ){
	// nastaveni parent divu
	var imgNode = '.loadImg';
	var pDiv = '';
	var setHeight = true; 
	switch( pozice ){
		case 'sklad':
			pDiv = '#skladDiv'; 
			break;
		case 'objednavky':
			pDiv = '#objednavkyDiv';
			break;
		case 'zakaznici':
			pDiv = '#zakazniciDiv';
			break;
		case 'mailing':
			pDiv = '#mailingDiv';
			break;
		case 'mailingCreator':
			pDiv = '#mailingCDiv';
			break;
		default:
			return false;
			break;
	}
	// uprava divu
	$(pDiv).css('position','relative');
	$(pDiv+' .load').each(function(){
		if( setHeight){
			var h = $(this.parentNode).height();
			if( h < 400 ){
				h=400;
				$(this.parentNode).height(h);
			}
			$(this).height(h);
		}
		$(this).css('position','absolute');
		$(this).css('text-align','center');
		$(this).css('top',$(this.parentNode).scrollTop() );
		$(this).css('left', 4000 );
		$(this).css('width',$(this.parentNode).width());
		$(this).css('background-color','white');
		$(this).css('border','1px solid #DDD');
		$(this).css('opacity','0.5');
		$(this).css('display','block');
		$(this.childNodes).each(function(){
			if(defined(this.tagName)){
				if( this.tagName.toLowerCase() == 'img'){
					if($(this).height()> 0 ){
						var vyska = (h/2 - $(this).height()/2);
						//if( vyska > 100 ) vyska = 100;
						$(this).css('margin-top',vyska );
					}
				}
			}
		});
		$(this).css('display','none');
		
		$(this).css('left',0 );
		if( showDiv ){
			 $(this).show();
		}
	});
}



// AJAX fce pro FORM 
function mdAjaxFormBefore(id){
	var html = '<div class="zmiz"><strong style="color:green">Data se odesílají...</strong><br/><img src="'+zacatekUrl+'images/_loading.gif" alt="..." /></div>\r\n';

	if( $('#TB_ajaxContent').size() > 0 ){
		$('#msgBoxText').html(html);
	}else{
		$('#msgBoxText').html(html);
		var url = "#TB_inline?height=100&width=350&inlineId=msgBox&modal=true";
		tb_show("", url);
	}
}
function mdAjaxFormSuccess(id,xml){
	var errorMsg = '';
	var errorHtml = '';
	var okMsg = '';
	$('rows',xml).each(function() {
		errorMsg = $('error',this).text();
		okMsg = $('msg',this).text();
		if(  $('error_data',this).text() ){
			if( typeOf(window.atob) != 'undefined' ){
				errorHtml = atob($('error_data',this).text());
			}else{
				errorHtml = "Function atob not found! Base64 data:\n" + $('error_data',this).text();
			}
		}
    });
	if( errorMsg == '' ){
		if( !okMsg ) okMsg = 'Data uložena'; 
		$('#msgBoxText').html('<div class="zmiz"><strong style="color:green">'+okMsg+'</strong><br/><input type="button" class="tbClose" name="tbClose" value="OK" /></div>\r\n');
		zmiz(500,500,true);		
		switch( $(id).attr('id')){
			case 'fragment-sklad':
				skladRefreshExtern();
				break;
			case 'fragment-objednavky':
				break;
		}	
	}else{
		$('#msgBoxText').html('<div class="zmiz">'+errorHtml+'<strong style="color:red">'+errorMsg+'</strong><br/><input type="button" class="tbClose" name="tbClose" value="OK" /></div>\r\n');
	}
	if( calbackSaveFunction ){
		eval(calbackSaveFunction+'();');
		calbackSaveFunction = ''
	}
	
}
function mdAjaxFormError(id){
	$('#msgBoxText').html('<div class="zmiz"><strong style="color:red">Chyba při přenosu dat.</strong><br/><input type="button" class="tbClose" name="tbClose" value="OK" /></div>\r\n');
}

function is_object( mixed_var ){
    // Returns true if variable is an object  
    // 
    // version: 810.114
    // discuss at: http://phpjs.org/functions/is_object
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Legaev Andrey
    // +   improved by: Michael White (http://getsprink.com)
    // *     example 1: is_object('23');
    // *     returns 1: false
    // *     example 2: is_object({foo: 'bar'});
    // *     returns 2: true
    // *     example 3: is_object(null);
    // *     returns 3: false
    if(mixed_var instanceof Array) {
		return false;
	} else {
		return (mixed_var !== null) && (typeof (mixed_var) == 'object');
	}
}




// schova a smaze blok s class .zmiz
function zmiz( waitTime, removeTime, tbClose ){
	removeTime = removeTime || 500;
	$('.zmiz')
		.wait(waitTime)
		.hide(removeTime, function () {
			$(this).remove();
			if( tbClose )tb_remove();
		});
	
}


