String.prototype.trim = function() {
	return this.replace(/^\s+|\s+$/g,"");
}
String.prototype.ltrim = function() {
	return this.replace(/^\s+/,"");
}
String.prototype.rtrim = function() {
	return this.replace(/\s+$/,"");
}


function switchOffFlash(off) {
	var objectarray = document.getElementsByTagName("object");
	if(objectarray) {
		for(var i in objectarray) {
			//alert(objectarray[i].style);
			if(objectarray[i].style) {
				if(objectarray[i].style.visibility) {
					if(objectarray[i].style.visibility != null) {
						objectarray[i].style.visibility = (off) ? "hidden" : "";
					}
				}
			}
		}
	}
}
/**
 * MainMenu
 */
var tm1=0

function hideShow(id,key)
{
    var element = document.getElementById(id);
if(element != null)
    if(element.className=="makeMenu")
    {
      element.style.display=key;
    }

}

function doMenu(id)
{
    for(var i=1;i != menu_count+1;i++)
    {
        var nameid = "m"+i;
        var key = 'none';
        
        if(nameid==id){
		key='block';        
        hideShow(nameid,key);
        document.getElementById("acko"+i).style.textDecoration='none'; 		// styl pri otevrenem menu
        }
        else {
		document.getElementById("acko"+i).style.textDecoration='none';		// styl pri zavrenem menu
		key='none';
		hideShow(nameid,key);
		}
    }
    if (id != '') cancelOut()    	
}

function cancelOut()
{
	if (tm1 != 0)
	{
		clearTimeout(tm1)
		tm1 = 0
	}
}

function hidemenu()
{
	doMenu('')
} 

function mhide()
{
	cancelOut()
	tm1 =setTimeout("hidemenu()",334);
}

/**
 * Search
 */
function searchKeyEnter(myfield,e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13) {
   		sendCommand("CmdSearch");
   		return false;
    }
	else
   		return true;
}
/**
 * SearchResult
 */
function searchKeyEnterFromResult(myfield,e) {
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13) {
   		sendCommand("CmdSearchAgain");
   		return false;
    }
	else
   		return true;
}

/**
 * Login
 */
// odchytavani klavesy ENTER (13) v polích login a password
function loginKeyEnter(myfield,e)
{
	var keycode;
	if (window.event) keycode = window.event.keyCode;
	else if (e) keycode = e.which;
	else return true;

	if (keycode == 13 )
    {
   
   		sendCommand('CmdLogin',null);
   		return false;
    }
	else
   		return true;
}
/**
 * Objekt pro kontrolu hodnot.
 * Každá funkce vrací true nebo false 
 */ 
var Validate = {
	/**
	 *	Kontrolu emailu
	 *	@param  string
	 *	@return boolean
	 */ 	 	
	email : function( value ) {
		//var regexp = new RegExp(/([.a-z0-9_-]{3,251}\@[.a-z0-9_-]{3,251})/i);
		var regexp = new RegExp(/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\@([a-z0-9])(([a-z0-9-])*([a-z0-9]))+(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i);
		return regexp.test(value);
	},
	/**
	 *	Kontrolu PSČ (190000 nebo 190 00)
	 *	@param  string
	 *	@return boolean
	 */
	zipcode : function( value ) {
		var regexp = new RegExp(/^(^[0-9]{5,5}$)|(^[0-9]{3,3}\s{1,1}[0-9]{2,2}$)$/);
		return regexp.test(value);
	},
	/**
	 * Kontrola telefonního čísla
	 *	@param  string
	 *	@param  boolean Jestli je požadována mezinárodní předvolba	 
	 *	@return boolean
	 */
	phone : function( value, internation_required ) {
		//var regexp = new RegExp(/^([+]{0,1}[0-9]{3,3})?([0-9]{9,9})$/);
		if(typeof internation_required == 'undefined') var internation_required = false;
		// musí obsahovat mezinárodní předvolbu
		if(internation_required) {
			var regexp = new RegExp(/^([+]{1,1}[0-9]{3,3}[0-9]{9,9})$/);
		// může obsahovat mezinárodní předvolbu
		} else {
			var regexp = new RegExp(/^([+]{0,1}[0-9]{3,3})?([0-9]{9,9})$/);
		}
		return regexp.test(value);
	},
	/**
	 * Kontrola celého čísla
	 *  @param  mixed
	 *  @param  boolean
	 *	@return boolean
	 */
	intValue : function( value, correct ) {
		if(typeof correct == 'undefined') var correct = false;
		
	},
	/**
	 * Kontrola desetinného čísla
	 *  @param  mixed
	 *  @param  boolean
	 *	@return boolean
	 */	 
	floatValue : function( value, correct ) {
		if(typeof correct == 'undefined') var correct = false;
		var pvalue = parseFloat(value);
		if(isNaN(pvalue)) {
			return false;
		}
		if(pvalue.toString() != value.toString()) {
			return false;
		}
		return true;
	}
}
/**
 * Ziskání koretních hodnot s předané hodnoty
 */
var GetValue = {
	/**
	 * Celé číslo
	 * @param mixed
	 * @param boolean Jestli je povolena nula (value = 0)	
	 * @return integer	 
	 */
	intValue : function( value, allow_zero ) {
		value = value.toString();
		if(typeof allow_zero == 'undefined') var allow_zero = false;
	},
	/**
	 * Desetinné číslo
	 * @param mixed
	 * @param boolean Jestli je povolena nula (value = 0)
	 * @return float	 
	 */
	floatValue : function( value, allow_zero ) {
		value = value.toString();
		if(typeof allow_zero == 'undefined') var allow_zero = false;
	},
	/**
	 * Poštovní směrovací číslo
	 * @param mixed
	 * @param boolean Jestli je mezera mezi třetím a čtvrtým číslem
	 * @return string	 
	 */
	zipcode : function( value, allow_space ) {
		value = value.toString();
		if(typeof allow_space == 'undefined') var allow_space = false;
		var correctvalue = '';
		for(var i = 0; i < value.length; i++) {
			var charvalue = value.slice(i,i+1);
			if((i == 3 && charvalue == ' ' && allow_space) || !isNaN(parseInt(charvalue))) {
				correctvalue += charvalue;
			}
		}
		if(correctvalue.length > 5) {
			correctvalue = correctvalue.substr(0,5);
		}
		return correctvalue;
	}
}

/**
 * Objekt pro vypisování chyb ve formuláři
 */ 
var FormAlert = {
	c : 0,
	/**
	 * Přidání zprávy
	 * @param  string
	 * @param  string
	 * @return false 
	 */	 	 	 	
	add : function( id, text ) {
		if($("#form_alerts").has("li#form_each_alert_"+id).length == 0) {
			FormAlert.c++;
			if($("#form_alerts").has("ul").length > 0) {
				$("#form_alerts ul").append('<li id="form_each_alert_'+id+'" style="display: none">'+text+'</li>');
			}
			else {
				$("#form_alerts").append('<ul><li id="form_each_alert_'+id+'" style="display: none">'+text+'</li></ul>');
			}
			$("#form_each_alert_"+id).slideDown(200);
		}
		return false;
	},
	/**
	 * Odstranění zprávy
	 * @param  string
	 * @param  string
	 * @return true	 
	 */	 	 	 	
	remove : function( id ) {
		if($("#form_alerts ul").has("li#form_each_alert_"+id).length > 0) {
			FormAlert.c--;
			$("#form_alerts ul li#form_each_alert_"+id).slideUp(200,function(){
				$(this).remove();
				if(FormAlert.c == 0) {
					$("#form_alerts ul").remove();
				}
			});
		}
		else {
			if(FormAlert.c == 0) {
				$("#form_alerts ul").remove();
			}
		}
		return true;
	},
	/**
	 * Vrácení počtu zobrazených chyb
	 * @return boolean
	 */
	count : function() {
		try {
			// nelze použít kvůli slideDown a slideUp
			// return $("#form_alerts ul").children("li").length;
			if(FormAlert.c < 0) FormAlert.c = 0; 
			return FormAlert.c;
		} catch(e) {
			return 0;
		}
	},
	/**
	 * Zvýraznění chybových hlášek
	 */	 	
	highlight : function(color) {
		var bgcolor1 = $("#form_alerts").css("backgroundColor");
		var bgcolor2 = (typeof color == 'undefined') ? "#FFB87F" : color;
		$("#form_alerts").toggle(function() {
		    $(this).animate({ backgroundColor: "#FFFFFF" }, 1000);
		},function() {
		    $(this).animate({ backgroundColor: "#FFB87F" }, 500);
		});
	}
}
/**
 * Objekt pro zpracování registrace
 */ 
var Registration = {
	ok : false,
	update : false,
	checkingUsername : false,
	/**
	 * Zobrazení / skrytí chybové hláška
	 */	 	
	Warning : {
		add : function( id, text ) {
			return FormAlert.add("reg_message_"+id,text);
		},
		remove : function( id ) {
			return FormAlert.remove("reg_message_"+id);
		}
	},
	/**
	 * Zpracování uživatelského jména
	 */	 	
	Username : {
		ok : false,
		minLength : 4,
		maxLength : 20,
		isChecking : false,
		checkedValues : [],
		/**
		 * Kontrola délky.
		 * @param  string
		 * @return boolean
		 */		 		 		 		
		checkLength : function( value ) {
			value = value.trim();
			if(value.length == 0) {
				return Registration.Warning.add('un_l','Uživatelské jméno není vyplněné.');
			}
			else if(value.length < this.minLength || value.length > this.maxLength) {
				return Registration.Warning.add('un_l','Zadané uživatelské jméno může obsahovat nejméně 2 znaky a nejvíce 20 znaků.');
			}
			else {
				return Registration.Warning.remove('un_l');
			}
		},
		/**
		 * Zkontroluje, jestli již uživ. jméno existuje
		 * @param  string
		 * @return boolean
		 */		 		 		 		
		checkIfExists : function( value ) {
			var checked = false;
			for(var i = 0; i < this.checkedValues.length; i++) {
				if(this.checkedValues[i] == value) {
					checked = true;
				}
			}
			//if(!checked) {
				this.checkedValues.push( value );
				// omezení zahlcování požadavků
				//if(!Registration.checkingUsername) {
					Registration.checkingUsername = true;
					$.get("/ajax_request.php", { check_username : value }, function(data){
						Registration.checkingUsername = false;
						eval("var result = "+data+";");
						if(result) {
							Registration.Username.ok = false;
							return Registration.Warning.add('un_ex','Zadané uživatelské jméno existuje.');
						}
						else {
							Registration.Username.ok = true;
							return Registration.Warning.remove('un_ex');
						}
					});
				//}
			//}
		}
	},
	/**
	 * Zpracování hesla.
	 */	 	
	Password : {
		pass : null,
		minLength : 6,
		maxLength : 20,
		/**
		 * Kontrola hesla.
		 * @param  string
		 * @return boolean
		 */		 		 		 		
		check : function( value ) {
			value = value.trim();
			if(value.length == 0) {
				if(Registration.update) {
					return true;
				}
				return Registration.Warning.add('psw1','Není vyplněné heslo!');
			}
			else if(value.length < this.minLength) {
				return Registration.Warning.add('psw1','Zadané heslo je moc krátké!');
			}
			else if(value.length > this.maxLength) {
				return Registration.Warning.add('psw1','Zadané heslo je příliš dlouhé!');
			}
			else {
				return Registration.Warning.remove('psw1');
			}
		},
		/**
		 * Porovnání obou hesel.
		 * @param  string
		 * @param  string
		 * @return boolean
		 */		 		 		 		 		
		compare : function( value1, value2 ) {
			if(value1 != value2) {
				return Registration.Warning.add('psw2','Zopakované heslo není shodné!');
				
			}
			else {
				if(this.check(value1)) {
					return Registration.Warning.remove('psw2');
				}
				return false;
			}
		}
	},
	/**
	 * Zpracování kontaktních údajů.
	 */	 	
	ContactInfo : {
		ok : false,
		required : false,
		company : '',
		firstname : '',
		lastname : '',
		email : '',
		phone1 : '',
		phone2 : '',
		/**
		 * Kontrola všech polí
		 * @return boolean
		 */		 		 		
		check : function() {
			this.ok = true;
			this.firstname = $("#firstname").val().trim();
			this.lastname = $("#lastname").val().trim();
			this.email = $("#email").val().trim();
			this.phone1 = $("#phone1").val().trim();
			this.phone2 = $("#phone2").val().trim();
			
			if(this.firstname.length == 0) {
				Registration.Warning.add('cf','Není vyplněné jméno!');
				this.ok = false;
			} else {
				Registration.Warning.remove('cf');
			}

			if(this.lastname.length == 0) {
				Registration.Warning.add('cl','Není vyplněné přijmení!');
				this.ok = false;
			} else {
				Registration.Warning.remove('cl');
			}

			if(this.email.length == 0) {
				Registration.Warning.add('ce','Není vyplněný email!');
				this.ok = false;
			} else {
				Registration.Warning.remove('ce');
			}
			
			if(!Validate.email( this.email )) {
				Registration.Warning.add('ce','Email není ve správném formátu!');
				this.ok = false;
			} else {
				Registration.Warning.remove('ce');
			}
			return this.ok; 
		}
		
	},
	Address : {
		ok : false,
		required : false,
		type : 'N',
		check : function( type ) {
			this.type = type;
			if(this.type == 'N') {
				
				this.ok = true;
				
				if($("#addr1_street").val().trim() == '') {
					Registration.Warning.add('addr1s','Fakturační adresa: Není vyplněná ulice.');
					this.ok = false;
				} else {
					Registration.Warning.remove('addr1s');
				}
				
				if($("#addr1_housenumber").val().trim() == '') {
					Registration.Warning.add('addr1hn','Fakturační adresa: Není vyplněné číslo popisné ulice.');
					this.ok = false;
				} else {
					Registration.Warning.remove('addr1hn');
				}

				if($("#addr1_city").val().trim() == '') {
					Registration.Warning.add('addr1c','Fakturační adresa: Není vyplněné město.');
					this.ok = false;
				} else {
					Registration.Warning.remove('addr1c');
				}
				
				if($("#addr1_zipcode").val().trim() == '') {
					Registration.Warning.add('addr1z','Fakturační adresa: Není vyplněné PSČ.');
					this.ok = false;
				} else {
					Registration.Warning.remove('addr1z');
				}
				
				return this.ok;
			}
		}
	},
	/**
	 * Funkce pro odeslání formuláře.
	 * Nejprve proběhne kontrola a při úspěšném zpracování se formulář odešle.
	 */
	send : function() {
		var err = false;
		if(!Registration.Username.checkLength( $("#registration_username").val() )) {
			err = true;
		}
		else {
			Registration.Username.ok = true;
		}
		if(!Registration.Username.ok) {
			err = true;
		}
		if(!Registration.update || $("#registration_password1").val().trim().length > 0) {
			if(!Registration.Password.compare( $("#registration_password1").val(), $("#registration_password2").val() )) {
				err = true;
			}
		}
		if(Registration.ContactInfo.required) {
			if(!Registration.ContactInfo.check()) {
				err = true;
			}
		}
		if(Registration.Address.required) {
			if(!Registration.Address.check('N')) {
				err = true;
			}
		}
		if(!err) {
			sendCommand('CmdRegisterUser',null);
		}
	}
}
// Inicializace funkcí na formulářové prvky.
$(document).ready(function() {
	if($("#registration_username").is("input")) {
		$("#registration_username").keyup(function(e){
			Registration.Username.checkIfExists($(this).val());
		}).blur(function(){
			Registration.Username.checkIfExists($(this).val());
			Registration.Username.checkLength($(this).val());
		});
	}
	if($("#registration_password1").is("input")) {
		$("#registration_password1").blur(function() {
			Registration.Password.check($(this).val());
			if($("#registration_password2").val().trim().length > 0) {
				Registration.Password.compare($(this).val(),$("#registration_password2").val());
			}
		});
	}
	if($("#registration_password2").is("input")) {
		$("#registration_password2").blur(function() {
			if($(this).val().trim().length > 0 && $("#registration_password1").val().trim().length > 0) {
				Registration.Password.compare($("#registration_password1").val(),$(this).val());
			}
		});
	}
	
	try {
		$("#address1 label.boxtitle").click(function(){
			$("#address1_container").slideToggle(300);
		});
		$("#address2 label.boxtitle").click(function(){
			$("#address2_container").slideToggle(300);
		});
	}
	catch(e) {
		try {
			$("#address1_container").show();
			$("#address2_container").show();
		}
		catch(e) { }
	}
});



/**
 * Dialogové okno pro frontend.
 * Statická třída.
 *
 * @example
 *   Dialog.open('obsah dialog','Nadpis dialogu',objekt, callback);
 */
var Dialog = {
	speed_open_bg : 0,
	speed_open_win : 0,
	speed_close_bg : 200,
	speed_close_win : 200,
	/**
	 * Otevření dialogu
	 * @param  string Obsah
	 * @param  string Nadpis
	 * @param  objekt Objekt, kde se kliklo
	 * @param  objekt Callback
	 * @return objekt this
	 */
	open : function(content, header, e, callback) {
		if(typeof header == 'undefined') var header = 'Dialog';
		var id = Math.ceil(Math.random()*100000);
		var html = '';
		html += '<div class="dialog_bg" style="height: '+$("body").outerHeight()+'px; width: '+$("body").outerWidth()+'px" id="dialog_bg_'+id+'"></div>';
		html += '<div class="dialog_window" style="display: none" id="dialog_window_'+id+'">';
		html += ' <div class="close" onclick="Dialog.close('+id+');"></div>';
		html += ' <div class="container">';
		html += '  <div class="header">';
		html += '  '+header;
		html += '  </div>';
		html += '  <div class="content">';
		html += '  '+content;
		html += '  </div>';
		html += ' </div>';
		html += '</div>';
		/* vložíme pozadí, ale okno zůstane zatím skryté */
		$("#dialogs").html( html );
		/*
		var window_width = $("#dialogs div.dialog_window").outerWidth();
		var body_width = $("body").outerWidth();
		var percent_body_width = parseInt($("body").outerWidth() / 100);
		var left = (50 * percent_body_width) - parseInt(window_width / 2);
		/* position absolute pouze pro IE6 a starší */
		var position = ($.browser.msie) ? ((parseFloat($.browser.version) > 7) ? "absolute" : "fixed") : "fixed";
		/*
		var top = (position == "fixed") ? "20%" : "40%";
		$("#dialogs div.dialog_window").css( { 'left' : (left / percent_body_width)+'%', 'position' : position, 'top' : top } ).show();
		*/
		$("#dialogs div.dialog_window").css( {'position' : position} ).show();
		return this;
	},
	/**
	 * Zavření dialogu
	 * @param  mixed Objekt nebo ID
	 * @param  objekt Callback
	 * @return boolean
	 */
	close : function(param,callback) {
		if(typeof callback == 'undefined') {
			var callback = null;
		}
		if(typeof param == 'undefined') {
			this._close(null,callback);
		}
		else if(typeof param == 'object') {
			var w = $(param).parents("div[id^='dialog_window_']");
			//var w = $(param).parent();
			if(w.length == 1) {
				this._close($(w).attr("id"),callback);
			}
			else {
				this._close(null,callback);
			}
		}
		else {
			this._close(param,callback);
		}
	},
	_close : function(id,callback) {
		// pokud není předán parametr, zavřeme vše
		if(typeof id == 'undefined' || id == null) {
			$("#dialogs").html('');
			CallBack.call( callback );
			return true;
		}
		else {
			// zkusíme získat ID dialogu
			try {
				id = parseInt(id);
			}
			// pokud selže, zavřeme vše
			catch(e) {
				return this._close(null,callback);
			}
			// výsledek není platné číslo, zavřeme vše
			if(isNaN(id)) {
				return this._close(null,callback);
			}
			// zavřeme dialog s pozadím (předpokládáme, že jsou obě ID shodná....proč by nebyla?)
			try {
				$("#dialog_window_"+id).fadeOut(200,function(){
					$("#dialog_bg_"+id).fadeOut(200,function(){
						CallBack.call( callback );
					});
				});
			}
			catch(e) {
				return this._close(null,callback);
			}
			return true;
		}
	}
}
/**
 * Volání callbacku.
 * Statická třída.
 *
 * @example
 *   var source = { callback : 'MojeFunkce', params : [1,true,'hodnotaX','hodnotaY'] }
 *   Callback.call( source );
 */
var CallBack = {
	/**
	 * Volání samotného callbacku s parametry
	 * @param  mixed
	 * @return boolean
	 */
	call : function( source ) {
		if(typeof source == "object") {
			try {
				/* Vytvoříme objekt pro volání */
				var cb = CallBack._callback;
				/* Nastavíme funkci */
				cb._setFunction( source.callback );
				/* Připravíme parametry */
				var params = [];
				try {
					for(var i = 0; i < source.params.length; i++) {
						var p = source.params[i];
						if(typeof p == "string") {
							params.push("'"+p+"'");
						}
						if(typeof p == "boolean" || typeof p == "number" || typeof p == "boolean") {
							params.push(p.toString());
						}
					}
					/* Nastavíme parametry */
					cb._setParams( params.join(",") );
				}
				catch(e) { }
				/* Zavoláme výsledek */
				cb._call();
			}
			catch(e) {
				return false;
			}
			return true;
		}
	},
	/**
	 * Privátní objekt volaná uvnitř objektu Callback.
	 */
	_callback : {
		/**
		 * Název funkce
		 * @var function
		 */
		_fnc : null,
		/**
		 * Parametry funkce
		 * @var array
		 */
		_params : new Array(),
		/**
		 * Volání objektu.
		 */
		_call : function() {
			try {
				eval(this._fnc+"("+this._params+");");
			}
			catch(e) { }
		},
		/**
		 * Nastavení funkcí
		 * @param string Funkce
		 */
		_setFunction : function( fnc ) {
			try {
				this._fnc = fnc.toString();
			}
			catch(e) { }
		},
		/**
		 * Nastvení parametrů funkce
		 * @param string Parametry v jednom řetězci
		 */
		_setParams : function( params ) {
			try {
				this._params = params.toString();
			}
			catch(e) { }
		}
	}
}



