function is_numeric (mixed_var) {
    return (typeof(mixed_var) === 'number' || typeof(mixed_var) === 'string') && mixed_var !== '' && !isNaN(mixed_var);
}
function isEmail(value) {
	var regex = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
	return regex.test(value);
}
function urlencode (str) {
    str = (str+'').toString();
    return encodeURIComponent(str).replace(/!/g, '%21').replace(/'/g, '%27').replace(/\(/g, '%28').replace(/\)/g, '%29').replace(/\*/g, '%2A').replace(/%20/g, '-');
}
function urldecode (str) {
    return decodeURIComponent(str.replace(/\-/g, '%20'));
}
function implode (glue, pieces) {
    var i = '', retVal='', tGlue='';
    if (arguments.length === 1) {
        pieces = glue;
        glue = '';
    }
    if (typeof(pieces) === 'object') {
        if (pieces instanceof Array) {
            return pieces.join(glue);
        }
        else {
            for (i in pieces) {
                retVal += tGlue + pieces[i];
                tGlue = glue;
            }
            return retVal;
        }
    }
    else {
        return pieces;
    }
}
function explode (delimiter, string, limit) {
    var emptyArray = { 0: '' };

    // third argument is not required
    if ( arguments.length < 2 ||
        typeof arguments[0] == 'undefined' ||
        typeof arguments[1] == 'undefined' ) {
        return null;
    }

    if ( delimiter === '' ||
        delimiter === false ||
        delimiter === null ) {
        return false;
    }

    if ( typeof delimiter == 'function' ||
        typeof delimiter == 'object' ||
        typeof string == 'function' ||
        typeof string == 'object' ) {
        return emptyArray;
    }

    if ( delimiter === true ) {
        delimiter = '1';
    }

    if (!limit) {
        return string.toString().split(delimiter.toString());
    } else {
        // support for limit argument
        var splitted = string.toString().split(delimiter.toString());
        var partA = splitted.splice(0, limit - 1);
        var partB = splitted.join(delimiter.toString());
        partA.push(partB);
        return partA;
    }
}

function str_replace (search, replace, subject, count) {
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}
function formValidateField(o) {
	$(o).removeClass('bad').tipsy('hide');
	var v=$(o).val();
	if($(o).attr('id')=='pass1'){
		var p = $(o).prev().prev().val();
	}
	eval('var result=('+$(o).attr('validation')+');');
	if(result==false) {
		$(o).addClass('bad').tipsy('show');
	}
	return result;
}
function formValidateFieldAll(f){
	formAutohideFieldTextAll(f);
	$(f).find('[validation]').each(function(i) {
		formValidateField(this);
	});
	var invalidFields=$('.bad',f).length;
	if(invalidFields==0){
		return true;
	}else{
		return false;
	}
}
function formClearField(o,option){
	if(option==1){
		$(':input', o).each(function(){
			$(this).val('');
		});
	}else{
		$(o).val('');
	}
}
function formAutohideFieldText(o){
	var text = $(o).attr('autohide');
	if($(o).val()!=text)return false;
	$(o).val('');
	$(o).removeClass('autohide');
}
function formAutohideFieldTextAll(f){
	$(':input[autohide]',f).each(function(){
		formAutohideFieldText(this);
	});
}
function formSubmitText(o, option) {
 	$(o).html($(o).attr(option));
	if(option!='default')setTimeout(function(){ formSubmitText(o, 'default') }, 3000);
}
function formShowHideTipsy(o, option) {
 	$(o).tipsy(option);
	if(option!='hide')setTimeout(function(){ formShowHideTipsy(o, 'hide') }, 3000);
}
function formShowHideTipsyAll(f, option){
	$(':input[tipsy]',f).each(function(){
		formShowHideTipsy(this, option);
	});
}
function addLabel(o,oLabel,oClass,oLink,oOption) {
	var optionLink = '';
	if(oOption==1) optionLink = '<a class="remove" href="#">x</a>';
	if(oOption==2) optionLink = '<a class="edit" href="#">v</a>';
	var spanHtml = oLabel.find('span').html();
	if(oLink==1&&oLabel.find('span a').length>0){
		spanHtml = oLabel.find('span a').html();
	}
	var tempHTML = '<span class="label" ref="'+oLabel.attr('ref')+'" style="'+oLabel.attr('style')+'"><span style="'+oLabel.attr('style')+'" class="inLabel"><span>'+spanHtml+'</span>'+optionLink+'</span></span>';
	var html = $('.'+oClass,o).html();
	$('.'+oClass,o).html(html+tempHTML);
	return false;
}
function delLabel(label,receipt){
	$.ajax({
		type: "POST",
		url: "/"+myPath+"ajax/newLR.php",
		data: "label="+label+"&receipt="+receipt,
		cache: false,
		success: function(html) {
			}
		}
	);
	return false;
}


$(document).ready(function(){
		/// autohide hodnity
		$(':input[autohide]').each(function(){
			var text = $(this).attr('autohide');
			if($(this).val()==text)	$(this).addClass('autohide');
		});

		$(':input[autohide]').focus(function(){
			formAutohideFieldText(this);
		});
		//tipsy
		$('#newReceipt :input[validation]').tipsy({trigger: 'manual', gravity: 'n', html: true});
		$(':input[validation]').tipsy({trigger: 'manual', gravity: 'w', html: true});

		/*$('.mainMenu .expand').click(function(){
			$(this).parent().find('ul').toggle("blind", "", "fast");
			if($(this).hasClass('expanded')){
				$(this).removeClass('expanded');
			}else{
				$(this).addClass('expanded');
			}
		});*/
		//////////////////////////////////////////////////
		// R E G I S T R A C I A ////////////////////////
		////////////////////////////////////////////////
		$("form#singup input, form#accSettingsForm input:password").focus(function(){
			$(this).removeClass("bad").removeClass("good");
		});
		$("form#singup input:text").blur(function(){
				var id = $(this).attr("id"), val = $(this).val();
				var thisInput = $(this);
				if(formValidateField(this)) {
					$.ajax({
						type: "POST",
						url: "/"+myPath+"ajax/singup.php",
						data: id+"="+val,
						cache: false,
						success: function(html) {
							if(html!=1){
								$(thisInput).attr('tipsy',html);
								$(thisInput).tipsy('show');
							}
						}
					});
				}
			}
		);

		$("#singup input:password, #accSettingsForm input:password").focusout(function(){
			formValidateField(this);
		});
		$("#singup .submit").click(function(){
			var thisForm = $(this).parents('form');
			if(formValidateFieldAll(thisForm)) {
				$(thisForm).submit();
			}else {
				formSubmitText($('.submit',thisForm),'alert');
				return false;
			}
			return false;
		});
		$("#singin .submit").click(function(){
			var thisForm = $(this).parents('form');
			if(formValidateFieldAll(thisForm)) {
				$(thisForm).submit();
			}else {
				//formSubmitText($('.submit',thisForm),'alert');
				return false;
			}
			return false;
		});

////////////////////////////////////////////////////////////////////////////
//////////////////////kontakt//////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////

	$('#contactForm :input[validation]').blur(function(){
		formValidateField(this);
	});
	$('#contactForm .submit').click(function(){
		var thisForm = $(this).parents('form');
		if(formValidateFieldAll(thisForm)){
			$.ajax({
				type: "POST",
				url: '/'+myPath+'ajax/contact.php',
				data: ($(thisForm).serialize()),
				dataType: "text",
				cache: false,
				success: function(html) {
					if(html==1){
						formClearField(thisForm, 1);
						formSubmitText($('.submit',thisForm), 'response');
					}
				}
			});
		}else{
			formSubmitText($('.submit',thisForm), 'alert');
		}
		return false;
	});



//////////////////////////////////////////////////////////////////////////
/////////////////REPORT///////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////
//////////////////////////////////////////////////////////////////////////


		$("#setReceiptName, #setReceiptValue").blur(function(){
			formValidateField(this);
		});

		$("#newReceipt .submit").click(function(){
				var thisForm = $(this).parents('form');
				if(formValidateFieldAll(thisForm)) {
					//najdem vsetky nalebky kt. priradil k bloku
					var labels = Array();
					$('.label',thisForm).each(function(i) {
						labels[i] = $(this).attr('ref');
					});
					labels = implode('~',labels);

					$.ajax({
						type: "POST",
						url: "/"+myPath+'ajax/newReceipt.php',
						data: ($(thisForm).serialize())+'&labels='+labels,
						dataType: "text",
						cache: false,
						success: function(html) {
								if(html=='OK') {
									window.location = root;
								}
							}
						}
					);
				}
				return false;
			}
		);

		$('.labels .label').draggable({
	        helper: "clone",
	        opacity: 0.5,
	        cursor: 'move',
	        start: function(event, ui) {
	            oNewLabel = $(this);
	        }
		});

		$("#newReceipt :input,#newReceipt .newLabels").droppable({
			accept: '#mainLabels .label',
			drop: function(event, ui) {
				var thisForm = $(this).parents('form.newReceipt');
				var duplicity = false;
	            if($('.newLabels',thisForm).length>0) {
	            	if($('.newLabels .default_text',thisForm).length>0){
						$('.newLabels',thisForm).html('');
	            	}
	                $('.newLabels .label',thisForm).each(function() {
	                    if($(this).attr('ref') == oNewLabel.attr('ref')) duplicity = true;
	                });
	            }
	            if(!duplicity) {
					addLabel($(thisForm),oNewLabel,'newLabels',1,1);
	            }
			}
		});
		$("#receipts tr.droppable").droppable({
			accept: '#mainLabels .label',
			hoverClass: 'dHover',
			drop: function(event, ui) {
				var duplicity = false;
	            if($('.labels',this).length>0) {
	                $('.labels .label',this).each(function() {
	                    if($(this).attr('ref') == oNewLabel.attr('ref')) duplicity = true;
	                });
	            }
	            if(!duplicity) {
					$.ajax({
						type: "POST",
						url: "/"+myPath+"ajax/newLR.php",
						data: 'label='+oNewLabel.attr('ref')+'&li='+$(this).attr('ref'),
						dataType: "text",
						cache: false,
						success: function(html) {
								if(html=='OK') {
								}
							}
						}
					);
					addLabel($(this),oNewLabel,'labels',1,0);
	            }
			}
		});
		$('.label a.remove').live('click',function(){
			$(this).parents('.label').remove();
			return false;
		});
		//datepicker
		$(".date_picker").datepicker({
			showButtonPanel: true
		});
		//help pre pridavanie blokov
		$("#newReceipt .vtipToogle, #newReceipt .close").live("click", function(){
				formShowHideTipsyAll($('#body'),'hide');
				$("#newReceipt .helpContent").toggle("blind", "", "fast");
			}
		);
		$('#receipts tr').click(function(){
			var vrap = null;
			if($(this).hasClass('expanded')){
				vrap = 'nowrap';
				$(this).removeClass('expanded');
			}else{
				vrap = 'normal';
				$(this).addClass('expanded');
			}
			//$('td',this).each(function(){$(this).css('white-space',vrap)});
		});
		// L A B E L S menu ////////////////////////////////
		// E D I T labels /////////////////////
		$(".editLabel,.editLabelLink").fancybox({
			'onStart'			: function() {formShowHideTipsyAll($('#body'), 'hide');},
			'onClosed'			: function() {formShowHideTipsyAll($('#body'), 'hide');}
		});

		$('#mainLabels .editLabel').click(function(){
			$('#editLabel .setLabelName').val('');
		});

		$('#editLabel a.reset').click(function(){
			$.fancybox.close();
			return false;
		});

		$('#mainLabels .editLabelLink').click(function(){
			var labelName = $(this).parent().prev().find('a').html();
			var labelId = $(this).parent().prev().attr('ref');
			$('#editLabel .setLabelName').val(labelName);
			$('#editLabel .setLabelId').val(labelId);
			return false;
		});

		$("#editLabel .submit").click(function(){
			var thisForm = $(this).parents('form');
			if(formValidateFieldAll(thisForm)){
				$.ajax({
					type: "POST",
					url: "/"+myPath+"ajax/newLabel.php",
					data: $(thisForm).serialize(),
					cache: false,
					success: function(html){
						if(html=="OK"){
							window.location = root;
						}
					}
				});
			}
			return false;
        });

		$('.labels .label a.optionLabel').live('click',function(){
			$('#mainLabels .mainLabel').each(function(){
				$('.editOptions',this).css('display','none');
			});
			var thisLabel = $(this).parents('.mainLabel');
			var labelWidth = $('.label',thisLabel).outerWidth();
			$('.editOptions',thisLabel).css({'display':'block','left': labelWidth+'px'});
			$('body').live('click', function(){
				$('.editOptions').css('display','none');
			});
			return false;
		});

		$('#mainLabels .demoLabel').click(function(){
			var labelId = $(this).parent().prev().attr('ref');
			$.ajax({
				type: "POST",
				url: "/"+myPath+"ajax/newLabel.php",
				data: 'color='+$(this).attr('ref')+'&labelId='+labelId,
				cache: false,
				success: function(html){
					if(html=="OK"){
						window.location = root;
					}
				}
			});
		});
		// R E M O V E  labels ////////////////////////////////////
		$('#mainLabels .removeLabelLink').click(function(){
			var remove = confirm("chcete zmazať tuto nalepku?");
			if(!remove) return false;
			var labelId = $(this).parent().prev().attr('ref');
			$.ajax({
				type: "POST",
				url: "/"+myPath+"ajax/newLabel.php",
				data: 'remove='+labelId,
				cache: false,
				success: function(html){
					if(html=="OK"){
						window.location = root;
					}
				}
			});
			return false;
		});


		$("#editLabelCancel").click(function(){
			$.fancybox.close();
			return false;
		});
		// edit receipt /////////////////////////////////////////

		$(".editReceipt").fancybox({
			'autoDimensions'	: false,
			'width'         	: 'auto',
			'height'        	: 'auto',
			'transitionIn'		: 'none',
			'transitionOut'		: 'none',
			'onStart'			: function() {formShowHideTipsyAll($('#body'), 'hide');},
			'onClosed'			: function() {formShowHideTipsyAll($('#body'), 'hide');}
		});
		var defaultText =  null;
		$('#receipts tr a.editReceipt').click(function(){
			var thisTr = $(this).parents('tr');
			var editForm = $('#editReceipt form');
			$('.setReceiptName',editForm).val($('.inName',thisTr).html());
			$('.setReceiptNote',editForm).val($('.note',thisTr).html());
			$('.setReceiptValue',editForm).val($('.value',thisTr).html());
			$('.date_picker',editForm).val($('.date',thisTr).attr('date'));
			$('.editInput',editForm).val($(thisTr).attr('ref'));
			if(defaultText==null)defaultText = $('.newLabels',editForm).html();
			$('.newLabels',editForm).html(defaultText);
			$('.labels .label',thisTr).each(function(){
				if($('.newLabels .default_text',editForm).length>0)$('.newLabels',editForm).html('');
				addLabel($(editForm),$(this),'newLabels',1,1);
			});
			$.fancybox.resize();
			return false;
		});

		$("#editReceipt .submit").click(function(){
				var thisForm = $(this).parents('form');
				if(formValidateFieldAll(thisForm)) {
					//najdem vsetky nalebky kt. priradil k bloku
					var labels = Array();
					$('.label',thisForm).each(function(i) {
						labels[i] = $(this).attr('ref');
					});
					labels = implode('~',labels);

					$.ajax({
						type: "POST",
						url: "/"+myPath+'ajax/newReceipt.php',
						data: ($(thisForm).serialize())+'&labels='+labels,
						dataType: "text",
						cache: false,
						success: function(html) {
								if(html=='OK') {
									window.location = root;
								}
							}
						}
					);
				}
				return false;
			}
		);

		$('#editReceipt a.reset').click(function(){
			$.fancybox.close();
			return false;
		});

		$("#editReceipt :input,#editReceipt .newLabels").droppable({
			accept: '#editReceipt .label',
			drop: function(event, ui) {
				var thisForm = $(this).parents('form.newReceipt');
				var duplicity = false;
	            if($('.newLabels',thisForm).length>0) {
	            	if($('.newLabels .default_text',thisForm).length>0){
						$('.newLabels',thisForm).html('');
	            	}
	                $('.newLabels .label',thisForm).each(function() {
	                    if($(this).attr('ref') == oNewLabel.attr('ref')) duplicity = true;
	                });
	            }
	            if(!duplicity) {
					addLabel($(thisForm),oNewLabel,'newLabels',1,1);
	            }
				$.fancybox.resize();
			}
		});

		// receipt remove //////////////////////////////////////////

		$('#receipts tr a.removeReceipt').click(function(){
			var remove = confirm("chcete zmazať tento blok?");
			if(!remove)return false;
			var thisTr = $(this).parents('tr');
			$.ajax({
				type: "POST",
				url: "/"+myPath+'ajax/newReceipt.php',
				data: 'remove='+$(thisTr).attr('ref'),
				dataType: "text",
				cache: false,
				success: function(html) {
						if(html=='OK') {
						}
					}
				}
			);
			$(thisTr).hide('blind');
			return false;
		});
		/////////////////////////////////////////////
		//S E T T I N G S///////////////////////////
		//ACC//////////////////////////////////////

		$("#tabs").tabs();

		$(':input.ajaxSave').change(function(){
			if(!formValidateField(this))return;
			var thisInput = $(this);
			var name = $(this).attr('name');
			var value = $(this).val();
			$.ajax({
				type: "POST",
				url: "/"+myPath+"ajax/settings/accEdit.php",
				data: name+'='+value,
				cache: false,
				success: function(html) {
						var tipsy = $(thisInput).attr('tipsy');
						$(thisInput).attr('tipsy',html);
						formShowHideTipsy(thisInput,'show');
						$(thisInput).attr('tipsy',tipsy);
					}
			});
		});

		$("form#accSettingsForm .submit").click(function(){
			var thisForm = $(this).parents('form');
			if(formValidateFieldAll(thisForm)) {
				$.ajax({
					type: "POST",
					url: "/"+myPath+"ajax/settings/accEdit.php",
					data: $(thisForm).serialize(),
					cache: false,
					success: function(html) {
						if(html==1){
							formSubmitText($('form#accSettingsForm .submit'),'response');
						}else{
							formSubmitText($('form#accSettingsForm .submit'),'alert');
						}
					}
				});
			}
			//alert(old_email);
			return false;
		});

		//DELTETE ////////////////////////////////////////////

		$('form#accDeleteForm .submit').click(function(){
			var thisForm = $(this).parents('form');
			if(formValidateFieldAll(thisForm)){
				$.ajax({
					type: "POST",
					url: "/"+myPath+"ajax/settings/accDel.php",
					data: $(thisForm).serialize(),
					cache: false,
					success: function(html) {
						//alert(html);
						if(html=="OK"){
							window.location = root+"?logout=1";
						}else{
							var thisInput = $('#pass');
							var tipsy = $(thisInput).attr('tipsy');
							$(thisInput).attr('tipsy',html);
							formShowHideTipsy(thisInput,'show');
							$(thisInput).attr('tipsy',tipsy);
						}
					}
				});
			}
		});


		/* ==========   FEEDBACK   ===========*/
		$('#feedback .fTab').click(function(){
			formShowHideTipsyAll($('#feedback'), 'hide');
			var fBody = $('.fBody');
			$(fBody).toggle("blind", "", "normal");
		});

		$('#feedback .submit').click(function(){
			var thisForm = $(this).parents('form');
			if(formValidateFieldAll(thisForm)){
				$.ajax({
					type: "POST",
					url: "/"+myPath+"ajax/feedback.php",
					data: $(thisForm).serialize(),
					cache: false,
					success: function(html) {
						$('#fMsg').attr('autohide',html).val(html).addClass('cGray');
					}
				});
			}
			return false;
		});

		/* ==========   SEARCH   ===========*/
		$('#submitSearchForm').click(function(){
			//window.location = root+'report/search/'+urlencode($('#setSearch').val());
			$('#searchForm').submit();
		});
		$('#resetSearchForm').click(function(){
			$('#setSearch').val('');
			$('#searchForm').submit();
			return false;
		});

});










