function insert_at_cursor(myID, myValue,clear,selectionIE) {  
  myField=document.getElementById(myID);
	if(clear)myField.value='';
	if(typeof window.selection=='object' ){
		window.selection.text += myValue;
		myField.focus();
		var range = myField.createTextRange();
		range.move('character', myField.value.length);
		range.select();
		return false;
	}else if (document.selection) {
		myField.focus();
		sel = document.selection.createRange();
		sel.text = myValue;
  }else if (myField.selectionStart || myField.selectionStart == '0') {
    var startPos = myField.selectionStart;
    var endPos = myField.selectionEnd;
    myField.value = myField.value.substring(0, startPos)+ myValue+ myField.value.substring(endPos, myField.value.length);
  } else {
    myField.value += myValue;
  }
	myField.focus();
}
function check_full_form(elid){
	var fields = $(elid).getElements('input').append($(elid).getElements('select'));
	for (var i = 0; i < fields.length; i++) {
		if(fields[i].value==''){
			fields[i].disabled=true;
		}
	}				
}

function findPos2(obj) { 
	var sirka = curleft = curtop = 0; 
	if (obj.offsetParent) {
		curleft = obj.offsetLeft;
		 curtop = obj.offsetTop 
		  sirka = obj.offsetWidth;
		while (obj = obj.offsetParent) {
			 curleft += obj.offsetLeft;
			 curtop += obj.offsetTop;
			 //sirka = obj.offsetWidth;
			 } 
		} 
		return [curleft,curtop,sirka]; 
	}
function pocitadlo(el,hlaskaId,maximum){
	pos=findPos2(el);
	x=pos[2]+pos[0]-70;
	y=pos[1]-13;
	//alert(hlaskaId);
	var error='';
	var hlaska=document.getElementById(hlaskaId);
	hlaska.style.position='absolute';
	hlaska.style.display='inline';
	hlaska.style.backgroundColor='';  
	hlaska.style.fontSize="10px";
	hlaska.style.height="8px";
	hlaska.style.left=x+'px';
	hlaska.style.top=y+'px';
	hlaska.innerHTML=el.value.length+'/'+maximum;
	if(el.value.length>=maximum){
		alert('Text je příliš dlouhý. Bude zkrácen.');
		el.value=el.value.substring(0,maximum);
	}
}
function smazat(el){
	if(d=document.getElementById(el.name+"_pocitadlo")){
		d.parentNode.removeChild(d);
	}
}
function pocitadlo2(el,minimum,maximum,extraCheck){
	if(document.getElementById(el.name+"_pocitadlo")){
		infoBox=document.getElementById(el.name+"_pocitadlo");
	}else{
		var infoBox = document.createElement("span");
		infoBox.id=el.name+"_pocitadlo";
		el.parentNode.insertBefore(infoBox, el);
	}
	pos=findPos2(el);
	x=pos[0]-210;
	y=pos[1]-40;
	//alert(hlaskaId);
	var hlaska=infoBox;
	hlaska.style.position='absolute';
	hlaska.style.display='inline';
	hlaska.style.backgroundColor='yellow';  
	hlaska.style.borderLeft='1px solid silver';
	hlaska.style.borderTop='1px solid silver';
	hlaska.style.borderRight='1px solid silver';
	hlaska.style.borderBottom='1px solid silver'; 
	hlaska.style.fontSize="10px"; 
	hlaska.style.margin="0px";
	hlaska.style.padding="1px";
	hlaska.style.width="200px";
	hlaska.style.left=x+'px';
	hlaska.style.top=y+'px';
	error='';
	malo='';
	if(el.value.length>=maximum){
		//alert('Text je příliš dlouhý. Bude zkrácen.');
		el.value=el.value.substring(0,maximum);
	}
	if(extraCheck){
		switch(extraCheck){
			case'safeChars':
				if(!el.value.match(new RegExp("^[a-zA-Z0-9_]{0,}$"))){
					error="Chybný znak <br />";
				}
			break;
			case'nick':
				if(!el.value.match(new RegExp("^[\-a-zA-Z0-9_ě_š_č_ř_ž_ý_á_í_é_ť_ú_ů_ó_ď_ň_Ě_Š_Č_Ř_Ž_Ý_Á_Í_É_Ť_Ú_Ů_Ó_Ď_Ň\_\.]{0,}$"))){
					error="Chybný znak <br />";
				}			
			break;
			case'ico':
				if(!el.value.match(new RegExp("^[0-9]{8}$"))){
					error="IČO musí mít přesně 8 číslic <br />";
				}			
			break;
			case'cislo':
				if(!el.value.match(new RegExp("^[0-9]+$"))){
					error="Neplatný znak pro číslo <br />";
					toCena(el);
				}			
			break;			
			case'rok':
				if(!el.value.match(new RegExp("^[0-9]{4}$"))){ 
					error="Rok má 4 číslice <br />";
				}else{
					dnes = new Date();
					max=dnes.getFullYear()+1;
					if(el.value<1900||el.value>max){
					error="rok není v rozsahu 1900 až "+max;
					}
				}
			break;
			case'password':
				var pw=el.value
				var pwlength=(pw.length);
				if (pwlength>5)pwlength=5;
				var numnumeric = pw.replace (/[0-9]/g, "");
				var numeric=(pw.length - numnumeric.length);
				if (numeric>3)numeric=3;
				var symbols = pw.replace (/\W/g, "");
				var numsymbols=(pw.length - symbols.length);
				if (numsymbols>3)numsymbols=3;
				var numupper = pw.replace (/[A-Z]/g, "");
				var upper=(pw.length - numupper.length);
				if (upper>3)upper=3;
				var pwstrength=((pwlength*10)-20) + (numeric*10) + (numsymbols*15) + (upper*10);
				if ( pwstrength < 0 ) {pwstrength = 0;}
				if ( pwstrength > 100 ) {pwstrength = 100;}		
				error="Síla hesla je "+pwstrength+" ze 100 <br />";
			break;
		}
	}
	if(el.value.length<minimum){
		kolik=minimum-el.value.length;
		malo="Napište prosím ještě minimálně "+kolik+" znaků. <br />";
	}
	pocitadlo=el.value.length+'/'+maximum;
	hlaska.innerHTML="<span style='color:red'>"+error+malo+"</span>"+pocitadlo;
}
function toCena(el){
	var pom=parseInt(el.value);
	if(isNaN(pom)){
		el.value=0;
	}else if(pom<0){
		el.value=pom*-1; 
	}else{
		el.value=pom;
	}
}
function checkAll(id){
	frm=document.getElementById(id);
	var inputs = frm.getElementsByTagName("input");
	for (var i = 0; i < inputs.length; i++) {
		if (inputs[i].type == "checkbox"){
			if(inputs[i].name){
				if(inputs[i].checked){
					inputs[i].checked=false;
				}else{
					inputs[i].checked=true;
				}
			}
		}
	}
}
function AddFavorite(linkObj,addUrl,addTitle)
{
  if (document.all && !window.opera)
  {
    window.external.AddFavorite(addUrl,addTitle);
    return false;
  }
  else if (window.opera && window.print)
  {
    linkObj.title = addTitle;
    return true;
  }
  else if ((typeof window.sidebar == 'object') && (typeof window.sidebar.addPanel == 'function'))
  {
    if (window.confirm('Přidat oblíbenou stránku jako nový panel?'))
    {
      window.sidebar.addPanel(addTitle,addUrl,'');
      return false;
    }
  }
  window.alert('Po potvrzení stiskněte CTRL-D,\nstránka bude přidána k vašim oblíbeným odkazům.');
  return false;
}
function forumTemaKMotorce(oSelect){
		selectedIndex=oSelect.selectedIndex;//zjistim jaky index je aktualne vybrany
		selectedIdModel=oSelect.options[selectedIndex].value;//jaka hodnota je vybrana?
		//alert(selectedIdModel);
		if(selectedIdModel=="0"){
			if(znacka=prompt('Zadej značku(Příklad: "Moto Guzzi" jako "guz" nebo "Kawasaki" jako "kaw". Nejlepší je jen část názvu.)','')){
				if(model=prompt('Zadej model(Příklad: "GSF 650 Bandit" jako "gsf" nebo "GSX-R 1000" jako "gsx". Nejlepší je jen část názvu)','')){
					ajax_copy_to('http://www.quadmania.cz/include/ajax/forum_select_motorka.php?znacka='+znacka+'&model='+model,oSelect,1);
				}else{
					oSelect.selectedIndex=0;
				}
			}else{
				oSelect.selectedIndex=0;
			}
		}
}

function validateInput(value,type){
	switch(type){
		//http://www.congayclave.eu/foto/foto5/parte4/f1/foto/foto%20(33).jpg
		case'required':oRe=new RegExp("^.+$");break;
		case'url':oRe=new RegExp("^http\:\/\/[^\ \;\"]+$");break;
		case'url-image':
			//problem je kdyz misto domeny je IP
			oRe=new RegExp("^http\:\/\/[^\ \;\"]+$");
		break;
		case'video-youtube':oRe=new RegExp("^http\:\/\/[^y]*youtube.com\/watch.*v\=[a-zA-Z0-_\-]+.*$");break;
		//http://video.google.com/videoplay?docid=8815587647189809806&hl=cs
		case'video-google':oRe=new RegExp("^http:\/\/video\.google\.com\/videoplay[\?]docid\=.*$");break;
		case'video-vimeo':oRe=new RegExp("^http\:\/\/vimeo\.com\/([0-9]+)$");break;
		//http://www.stream.cz/uservideo/121482-skodovka-vs-tatra
		case'video-stream':oRe=new RegExp("^http\:\/\/(www\.){0,1}stream\.cz\/(user){0,1}video\/([0-9]+\/){0,1}[0-9]+\-.*$");break;
		case'gps':
			oRe=new RegExp("^[-+]{0,1}[0-9]+°[0-9]+'[^\"]+\"[NS]{0,1},[-+]{0,1}[0-9]+°[0-9]+'[^\"]+\"[EW]{0,1}$");
			value=value.replace(/[ ]/g,'');
		break; 
		default:return true;
	}
	if(oRe.test(value)){
		return true;
	}else{
		return false;
	}
}
//version: default,videoSekce
function forumInserts(type,id,version){
	myField=document.getElementById(id);
  if (document.selection) {//kdyz IE tak si musim zapamatovat range pred spustenim dalsi area :( 
		myField.focus();
		window.selection = document.selection.createRange();
	}
	switch(type){
		case'url':
		 //insertAtCursor(id,"[url=http://www.adresa-odkazu.cz]text-odkazu[/url]");
			msg=new Zpravy('Vložte odkaz','info','Prosím vložte odkaz.<br/> Například: <strong>http://www.motorkari.cz/</strong>'); 
			msg.makeInputs(['Název stránky','Odkaz'],['text','text'],['','url'],'[url=#1]#0[/url] ',id,0);

		break;
		case'bold':
			//insertAtCursor(id,"[b]Tučný text[/b]");
			msg=new Zpravy('Vložte tučný text','info','Prosím vložte text, který bude tučně.'); 
			msg.makeInputs(['Text'],['textarea'],[],'[b]#0[/b] ',id,0);			
		break;
		case'big':
			//insertAtCursor(id,"[b]Tučný text[/b]");
			msg=new Zpravy('Vložte text který bude větší','info','Prosím vložte text, který bude větší.'); 
			msg.makeInputs(['Text'],['text'],[],'[big]#0[/big] ',id,0);			
		break;		
		case'direct-image':
			//insertAtCursor(id,"[img]http://adresa-obrazku.cz/obrazek.jpg[/img]");
			msg=new Zpravy('Vložte odkaz na obrázek','info','Prosím vložte přímý odkaz na obrázek.<br/> Například: <strong>http://www.motorkari.cz/images/logo.png</strong>'); 
			msg.makeInputs(['Odkaz na obrázek'],['text'],['url-image'],'[img]#0[/img] ',id,0);			
		break;
		case'citace':
			msg=new Zpravy('Vložte citovaný text','info',''); 
			msg.makeInputs(['Citovaný text'],['textarea'],[],'[quote]#0[/quote] ',id,0);
		break;
		case'p':
			msg=new Zpravy('Vložte odstavec','info',''); 
			msg.makeInputs(['Odstavec'],['textarea'],[],'[p]#0[/p] ',id,0);
		break;	
		case'seznam':
			msg=new Zpravy('Vložte seznam','info','Každý nový řádek je další položka seznamu'); 
			msg.makeInputs(['Seznam'],['textarea'],[],'[seznam]#0[/seznam] ',id,0);
		break;		
		case'youtube':
			//insertAtCursor(id,"[youtube]http://youtube.com/watch?v=HSoVKUVOnfQ[/youtube]");
			msg=new Zpravy('Vložte link na video','info','Prosím vložte odkaz na Youtube video.<br/> Například: <strong>http://www.youtube.com/watch?v=32B9pgpqpug</strong>'); 
			msg.makeInputs(['Odkaz na youtube video'],['text'],['video-youtube'],'[youtube]#0[/youtube] ',id,0);		
		break;
		case'stream':
			//insertAtCursor(id,"[stream]http://www.stream.cz/video/156610-fashion-mania-trenky-nebo-slipy[/stream]");
			msg=new Zpravy('Vložte link na video','info','Prosím vložte odkaz na Stream video.<br/> Například: <strong>http://www.stream.cz/video/156610-fashion-mania-trenky-nebo-slipy</strong>'); 
			msg.makeInputs(['Odkaz na stream video'],['text'],['video-stream'],'[stream]#0[/stream] ',id,0);			
		break;
		case'vimeo':
			//insertAtCursor(id,"[stream]http://www.stream.cz/video/156610-fashion-mania-trenky-nebo-slipy[/stream]");
			msg=new Zpravy('Vložte link na video','info','Prosím vložte odkaz na Vimeo video.<br/> Například: <strong>http://vimeo.com/11955621</strong>'); 
			msg.makeInputs(['Odkaz na Vimeo video'],['text'],['video-vimeo'],'[vimeo]#0[/vimeo] ',id,0);			
		break;		
		case'gps'://49°50'17.693"N, 16°56'47.653"E
			//insertAtCursor(id,"[gps]49°50'17.693\"N, 16°56'47.653\"E[/gps]");
			msg=new Zpravy('Vložte GPS Souřadnice','info','Prosím GPS souřadnice.<br/> Například: <strong>49°50\'17.693\"N, 16°56\'47.653\"E</strong>'); 
			msg.makeInputs(['GPS Souřadnice'],['text'],['gps'],'[gps]#0[/gps] ',id,0);			
		break;
		case'gps-direct'://49°50'17.693"N, 16°56'47.653"E
			//insertAtCursor(id,"[gps]49°50'17.693\"N, 16°56'47.653\"E[/gps]");
			msg=new Zpravy('Vložte GPS Souřadnice','info','Prosím GPS souřadnice.<br/> Například: <strong>49°50\'17.693\"N, 16°56\'47.653\"E</strong>'); 
			msg.makeInputs(['GPS Souřadnice'],['text'],['gps'],'#0',id,1);			
		break;
		case'youtube-direct':
			//insertAtCursor(id,"[youtube]http://youtube.com/watch?v=HSoVKUVOnfQ[/youtube]");
			msg=new Zpravy('Vložte link na video','info','Prosím vložte odkaz na Youtube video.<br/> Například: <strong>http://www.youtube.com/watch?v=32B9pgpqpug</strong>'); 
			msg.makeInputs(['Odkaz na youtube video'],['text'],['video-youtube'],'#0 ',id,1);		
		break;		
	}
	
	return false;
}
var Zpravy = new Class({
	initialize: function(nadpis,type,data){
		
			classOk='messageBox';
			classKo='messageBox';
			classInfo='messageBox';
			initialWidth=500;
			initialHeight=250;
			isForm=false;
			this.defaultValues=new Array();
			switch(type){
				default:
				case'info':tridaStylu=classInfo;break;
				case'good':tridaStylu=classOk;break;
				case'bad':tridaStylu=classKo;break;
			}
		this.skryj();
		if($(data)){
			text=$(data).innerHTML;
			//$(data).destroy();
		}else{
			text=data;
		}
		
		pozadi= new Element('div', {'id': 'lbOverlay', 'styles': {'display': ''}}).addEvent("click", this.close);
		var pozadiFx = new Fx.Tween(pozadi);
		pozadiFx.set('opacity',0.9);
		//fx = {pozadi: pozadi.effect('opacity', {duration: 20}).hide()};
		//fx.pozadi.start(0.7);				
		this.position();
		pozadi.inject(document.body);
		
		messageBox = new Element('div', {'class':tridaStylu});
		messageBox.setStyles({top: window.getScrollTop() + (window.getHeight() / 5), width: 600, marginLeft: ((window.getWidth()/2)-300), display: ""});
		messageBox.inject(document.body);
		messageBox_t_l = new Element('div', {'class': 'mb-t-l'}).inject(messageBox);
		messageBox_t_c = new Element('div', {'class': 'mb-t-c'}).inject(messageBox);
		messageBox_t_c_span = new Element('span').inject(messageBox_t_c);
		messageBox_t_c_span.set('html',nadpis);
		messageBox_t_c_close = new Element('div', {'class': 'mb-t-c-close'}).inject(messageBox_t_c);
		messageBox_t_c_close.addEvent("click", this.close);
		messageBox_t_r = new Element('div', {'class': 'mb-t-r'}).inject(messageBox);
		messageBox_c_l = new Element('div', {'class': 'mb-c-l'});
		messageBox_c_r = new Element('div', {'class': 'mb-c-r'}).inject(messageBox_c_l);
		messageBox_c_c = new Element('div', {'class': 'mb-c-c'}).inject(messageBox_c_r);
		messageBox_c_c_p = new Element('p',{'id':'detail-zpravy'}).inject(messageBox_c_c);
		messageBox_c_c_p.set('html',text);
		messageBox_c_l.inject(messageBox);
		messageBox_b_l = new Element('div', {'class': 'mb-b-l'});
		messageBox_b_r = new Element('div', {'class': 'mb-b-r'}).inject(messageBox_b_l);
		messageBox_b_c = new Element('div', {'class': 'mb-b-c'}).inject(messageBox_b_r);		
		messageBox_b_l.inject(messageBox);
		//fx.overlay.start(0.9);
		//return false;
	},
	insertForm:function(action){
		if(action){
			formular=new Element('form',{'method':'post','action':action}).inject(messageBox_c_c);
		}else{
			formular=new Element('form',{'method':'post'}).inject(messageBox_c_c);
		}
		isForm=true;
	},
	setDefaultValue:function(name,value){
		this.defaultValues.append(new Array({'jmeno': name, 'hodnota': value}));
	},
	getDefaultValue:function(name){
		for(var i=0;i<this.defaultValues.length;i++){
			item=this.defaultValues[i];
			if(name==item.jmeno)return item.hodnota;
		}
		return '';
	},
	makeInputs:function(aLabels,aTypes,aValidatorsParam,formatParam,idToInsert,clear,aNames){
		insertVystupTo=idToInsert;
		aVlidators=aValidatorsParam;
		format=formatParam;
		clearBeforeInsert=clear;
		window.inputs=new Array;
		if(isForm){
			messageBox_c_c=formular;
			selectedValue='';
		}else{
			selectedValue=$(idToInsert).getSelectedText();//nactu si selected hodnotu z elementu
		}
		for(i=0;i<aLabels.length;i++){
		//aLabels.each(function (label){
			label=aLabels[i];
			name=(typeof(aNames)==='object')?aNames[i]:'box[]';
			uid=String.uniqueID();
			typeOfInput=aTypes[i];
			oLabel=new Element('label',{'for':uid}).inject(messageBox_c_c);
			oLabel.set('html',label);
			if(selectedValue==''){selectedValue=this.getDefaultValue(name);}
			switch(typeOfInput){
				case'text':input=new Element('input',{'type':'text','name':name,'value':selectedValue,'id':uid});break;
				case'textarea':input=new Element('textarea',{'name':name,'cols':'50','rows':'5','id':uid});input.appendText(selectedValue);break;
			}
			selectedValue='';
			window.inputs.push(input.inject(messageBox_c_c));
			input.focus();
		};
		oSubmit=new Element('input',{'type':'submit','value':'   OK    ','class':'btn'}).inject(messageBox_c_c);
		if(isForm){//mam form tak nic neresim a cekamproste na submit
		}else{
			oSubmit.addEvent('click',this.doSubmit);
			oSubmit.addEvent('dblclick',this.closeSubmit);
		}
	},
	doSubmit:function(){
		window.doClose=true;
		for(i=0;i<window.inputs.length;i++){
			window.inputs[i].value=window.inputs[i].value.replace(/^\s+|\s+$/g,"");//vyhodim mezery nakonci a nazacatku trim()
			if(!validateInput(window.inputs[i].value,aVlidators[i])){
				window.inputs[i].style.border='1px solid red';
				window.doClose=false;
				
			}else{
				window.inputs[i].style.border='1px solid green';
				format=format.replace('#'+i,window.inputs[i].value);
			}
		}
		if(window.doClose)insert_at_cursor(insertVystupTo,format,clearBeforeInsert);
		//if(window.doClose)$(insertVystupTo).insertAtCursor(format,true);

		oSubmit.fireEvent('dblclick');
	},
	closeSubmit:function(){
		//alert(this.doClose);
		if(window.doClose){
			pozadi.parentNode.removeChild(pozadi);
			messageBox.parentNode.removeChild(messageBox);
			window.skryte.forEach(function(el){
				el.style.visibility='visible';
			});
			window['removeEvent']("scroll", this.position)['removeEvent']("resize", this.position);
		}
	},	
	close:function(){
			pozadi.parentNode.removeChild(pozadi);
			messageBox.parentNode.removeChild(messageBox);
			window.skryte.forEach(function(el){
				el.style.visibility='visible';
			});
			window['removeEvent']("scroll", this.position)['removeEvent']("resize", this.position);
	},
	skryj: function () {
		window.skryte=new Array;

		["object", window.ie ? "select" : "embed"].forEach(function(tag) {
			Array.forEach(document.getElementsByTagName(tag), function(el) {
				el.style.visibility = open ? "hidden" : elementsStyle[el];
				window.skryte.push(el);
			});
		});		
		//zmena pozice pri scrolovani
		window['addEvent']("scroll", this.position)['addEvent']("resize", this.position);		
	},
	position:function() {
		pozadi.setStyles({top: window.getScrollTop(), height: window.getHeight()});
	}	
})



