/***********************************\
*																*
*    JavaScript Document for edit textareas		*
*    Coder: Szymon Kosydor vel. BuBi 				*
*  	  szymon [_at_] kosydor [_dot_] pl				*
*																*
\***********************************/

function uploadVideo( form, inputName ) {
	var fileTypes = new Array( 'avi', 'mpg', 'mpeg', 'flv' );
	var iner = document.forms[ form ][ inputName ];
	var filePath = iner.value;
	var ta = filePath.split( '.' )
	var fileExt = ta[ ta.length - 1 ];
	if( !inArray( fileTypes, fileExt ) ) {
		alert( 'Możliwe typy plików to ' + fileTypes.join( ', ' ) );
	} else {
		document.forms[ form ].submit();
	}
}

function updatePhotoRel( class_n, selform, target ) {
	var ajax = new myAjax();
	ajax.action = 'updatePhotoRelation';
	var sel = document[ 'form_1' ][ selform ];
	for( j = 0; j < sel.length; j++ ) {
		if( sel.options[ j ].selected ) {
			selected = sel.options[ j ].value;
		}
	}
	ajax.post( 'class='+class_n+'&id='+selected, target );	

}

function insertMainPhotoPopup( target ) {
	if ( newokno ){ newokno.close(); }
	var opcje = "scrollbars=yes,width=500,height=500";	
	var newokno = window.open( document.root_folder+'/popup_main_photo/target'+target+'/', 'Zdjecie', opcje );
	//var newokno = window.open( document.root_folder+'/zdjecie/target'+target+'/', 'Zdjecie', opcje );
}

function insertMainPhotoPopupPublic( target ) {
	if ( newokno ){ newokno.close(); }
	var opcje = "scrollbars=yes,width=500,height=500";	
	//var newokno = window.open( document.root_folder+'/popup_main_photo/target'+target+'/', 'Zdjecie', opcje );
	var newokno = window.open( document.root_folder+'/zdjecie/target'+target+'/', 'Zdjecie', opcje );
}


function calPopup( id, width, height ) {
	if ( newokno ){ newokno.close(); }
	width  +=20;
	height +=20;
	var opcje = "scrollbars=yes,width="+width+",height="+height;	
	var url = document.root_folder+'/popup_photo/id/'+id+'/';
	var newokno = window.open( url, 'Zdjecie', opcje );
}

function insertMainPhoto( target, id, file_name, type ) {
	//window.opener.insertPhotoToForm(id, 'intro');
	var t 	= window.opener.document.getElementById( target );
	var s 	= window.opener.document.getElementById( target+'_sample' );
	var n 	= window.opener.document.getElementById( target+'_name' );
	t.value 	= id;
	n.value 	= file_name;
	s.src 		= '/img/small/'+id+'.'+type;
	window.close();
}

function deleteMainPhoto( target ) {
	var t 	= get( target );
	var s 	= get( target+'_sample' );
	var n 	= get( target+'_name' );
	t.value = '';
	n.value = '';
	s.src= document.root_folder+'/graph/sample.jpg';
}
function helpEdit() {
	popup( document.root_folder+'/popup/helpEdit.html' );
}

function editer_insertPhoto( target ) {
	insertPhotoToForm(1, target);
	
	/*var newokno;
	if (newokno){ newokno.close(); }
	var tytul = "Dostosuj";
	var opcje = "scrollbars=yes,width=500,height=500";
	newokno = window.open( document.root_folder+'/zdjecie/target/'+target+'/', tytul, opcje );*/
}

function generatePhotoSize( fname, id ) {
	var size = getValue( fname );
	ajax = new myAjax();
	ajax.action = 'generatePhotoSize';
	ajax.post( 'size='+size+'&id='+id );
}

// do fckeditora
function getFCKSelect() {
	var oEditor		= window.parent.InnerDialogLoaded() ;	
    if (document.getSelection) methodeselection = oEditor.FCK.EditorDocument.getSelection();
    else if (document.selection) methodeselection = oEditor.FCK.EditorDocument.selection.createRange().text;
    else return;
    return methodeselection;
  
}

function insertLinkToForm( classa, id, title ) {
//	alert( classa+' '+id+' '+title+' '+getFCKSelect() );
	var oEditor		= window.parent.InnerDialogLoaded() ;
	var FCK			= oEditor.FCK ;
	var sel = getFCKSelect();	
	a = FCK.InsertElement( 'a' );
	if( sel == '' ) {
		alert( sel );
		a.innerHTML = title;
	} else {
		a.innerHTML = sel;
	}
//	a.innerHTML = ( sel == '' ) ? title : sel;	
	a.href = '/FIND/'+classa.toString()+'/'+id.toString();
	window.top.close();
}

function insertRawLink() {
	var href = getValue( 'href' );
	var title = getValue( 'title' );
	var oEditor		= window.parent.InnerDialogLoaded() ;
	var FCK			= oEditor.FCK ;
	var sel = getFCKSelect();
	a = FCK.InsertElement( 'a' );	
	a.innerHTML = ( sel == '' ) ? title : sel;
	a.href = href;
	window.top.close();
}

function insertPhotoToForm( id, ext, title, addLightbox ) {
	var size = getValue( 'photo_size_'+id );
	

	if(document.getElementById(addLightbox).checked){
		var oEditor		= window.parent.InnerDialogLoaded() ;
	    var FCK			= oEditor.FCK ;
		a = FCK.InsertElement( 'a' );
		a.innerHTML = '<img src="/img/'+size+'/'+id+'.'+ext+'" alt="'+title+'"/>';
		a.className="thickbox"
		a.href = '/img/original/'+id+'.'+ext;
	}
	else{
		var oEditor		= window.parent.InnerDialogLoaded() ;
	    var FCK			= oEditor.FCK ;
		ph = FCK.InsertElement( 'img' );
		ph.alt = title;
		ph.src = '/img/'+size+'/'+id+'.'+ext;
	}
	window.top.close();
}

function previewFlash( fname, directory ) {
	var filename = getValue( fname );
	if( filename != '' ) {
		var width = getValue( 'width' );
		var height = getValue( 'height' );
		var fullfname = directory + filename;
		var FO = { movie:fullfname, width:width, height:height, majorversion:"6",wmode:"transparent",build:"0" };
	  	UFO.create(FO, "flash_preview");
	}
}

function insertFlashToForm( fname, directory ) {
	var filename = getValue( fname );
	var fullfname = directory + filename;
	var width = getValue( 'width' );
	var height = getValue( 'height' );
	var oEditor		= window.parent.InnerDialogLoaded() ;
	var FCK			= oEditor.FCK ;
	var oEmbed	= FCK.InsertElement( 'EMBED' );
	SetAttribute( oEmbed, 'type'			, 'application/x-shockwave-flash' ) ;
	SetAttribute( oEmbed, 'pluginspage'	, 'http://www.macromedia.com/go/getflashplayer' ) ;
	SetAttribute( oEmbed, 'src', fullfname );
	SetAttribute( oEmbed, "width" , width );
	SetAttribute( oEmbed, "height", height );
	FCK.OnAfterSetHTML();
	/*
	if (!document.selection) {
		oFakeImage	= oEditor.FCKDocumentProcessor_CreateFakeImage( 'FCK__Flash', oEmbed ) ;
		oFakeImage.setAttribute( '_fckflash', 'true', 0 ) ;
		oFakeImage	= FCK.InsertElement( oFakeImage ) ;
		oEditor.FCKFlashProcessor.RefreshView( oFakeImage, oEmbed ) ;
	 }*/
	window.top.close();
}

function SetAttribute( element, attName, attValue )
{
	if ( attValue == null || attValue.length == 0 )
		element.removeAttribute( attName, 0 ) ;			// 0 : Case Insensitive
	else
		element.setAttribute( attName, attValue, 0 ) ;	// 0 : Case Insensitive
}

function editer_horizontalLine( target ) {
	insertTextAtCursorPos( target, '[linia]', '' );
}

function editer_adv( target ) {
	insertTextAtCursorPos( target, '[reklama id=""]', '' );
}

function editer_newPage( target ) {
	insertTextAtCursorPos( target, '[koniec_strony]', '' );
}

function editer_subTitle( target ) {
	insertTextAtCursorPos( target, '[srodtytul]', '[/srodtytul]' );
}

function editer_table( target ) {
	insertTextAtCursorPos( target, "[tabelka naglowek=\"Tytuł\"]\n[wiersz]\n[komorka][/komorka]\n[komorka][/komorka]\n[/wiersz]\n[/tabelka]", '' );
}

function editer_iteration( target ) {
	insertTextAtCursorPos( target, "[wypunktowanie][punkt][/punkt][punkt][/punkt][/wypunktowanie]", '' );
}

function editer_numeration( target ) {
	insertTextAtCursorPos( target, "[numerowanie][punkt][/punkt][punkt][/punkt][/numerowanie]", '' );
}

function editer_href_in( target ) {
	insertTextAtCursorPos( target, "[a name=\"nazwa\"]\n[a href=\"#nazwa\"]Odwołanie[/a]", '' );
}

function editer_ramka( target ) {
	insertTextAtCursorPos( target, '[ramka wyrownanie="lewa" szerokosc="300"]', '[/ramka]' );		
}

function editer_wyrownanie( target ) {
	insertTextAtCursorPos( target, '[wyrownanie id="srodek"]', '[/wyrownanie]' );
}

function editer_enter1_5( target ) {
	insertTextAtCursorPos( target, '[enter15]' );
}

function editer_bold( target ) {
	insertTextAtCursorPos( target, '[b]', '[/b]' );
//	insertTextAtCursorPos( get( target ), '[b][/b]' );	
}

function editer_italic( target ) {
	insertTextAtCursorPos( target, '[i]', '[/i]' );	
}

function editer_underline( target ) {
	insertTextAtCursorPos( target, '[u]', '[/u]' );
}

function validateForm( form_name, names ) {
	hide( 'submiter_1' );
	hide( 'submiter_2' );
//	alert( 'validate ' + form_name );
	var sd = get( 'form_debug' );
	sd.innerHTML = '';
	
	var arr = names.split( '|' );
	var s = arr.length;
	var startText = "Proszę wypełnić pola :<br/>";
	var str = startText;
	
	for( i = 0; i < s - 1; i += 2 ) {
		var elem = get( arr[ i ] );
		if( trim( elem.value ) == '' ) {
			str += arr[ i + 1 ]+"<br/>";
		}
	}
	
	var p 	= get( 'password' );
	var p_r 	= get( 'password_repeat' );
	
	if( ( inArray( arr, 'password' ) ) && ( inArray( arr, 'password_repeat' ) ) && ( p.value !=  p_r.value ) ) {
		sd.innerHTML += 'Hasło nie zgadza się z powtórzeniem hasła<br/><br/>';
	} 
	
	if( str == startText ) {
		passed	= new Array( false, false, false );

		if( inArray( arr, 'password' ) ) {
			var ajax = new myAjax();
			ajax.action = 'validate_password';
			ajax.post( 'password='+get( 'password' ).value );
			ajax.onLoad = function() {
				if( this.response != 'ok' ) {
					show( sd );
					show( 'submiter_1' );
					show( 'submiter_2' );
					var resp = this.response.split( '|' );
					sd.innerHTML += "Hasło jest zbyt proste do odgadnięcia,<br/>użyj różnych wielkości liter, cyfr, albo dłuższego hasła<br/>Aktualna trudność hasła to ( "+resp[ 0 ]+" ) a wymagana ( "+resp[ 1 ]+" )<br/><br/>";
				} else {
					passed[ 0 ] = true;
					checkAllValidators( passed, form_name );					
				}
				delete ajax;
			}
		} else {
			passed[ 0 ] = true;
		}

		if( inArray( arr, 'email' ) ) {	
			var ajax = new myAjax();
			ajax.action = 'validate_email';
			ajax.post( 'email='+get( 'email' ).value );
			ajax.onLoad = function() {
				if( this.response != 'ok' ) {
					show( sd );
					show( 'submiter_1' );
					show( 'submiter_2' );
					sd.innerHTML += "To nie jest poprawny adres e-mail<br/><br/>";
				} else {
					passed[ 1 ] = true;
					checkAllValidators( passed, form_name );					
				}
				delete ajax;
			}
		} else {
			passed[ 1 ] = true;
		}
		
		if( ( getValue( 'action' ).substr( 0, 3 ) == 'add' ) && inArray( arr, 'nick' ) ) {
			var ajax = new myAjax();
			ajax.action = 'is_nick_in_base';
			ajax.post( 'nick='+get( 'nick' ).value );
			ajax.onLoad = function() {
				if( this.response == 'yes' ) {
					show( sd );
					show( 'submiter_1' );
					show( 'submiter_2' );
					sd.innerHTML += "Istnieje już osoba o takim nicku w bazie, wybierz inny<br/><br/>";
				} else if( this.response == 'no' ) {
					passed[ 2 ] = true;
					checkAllValidators( passed, form_name );
				}
				delete ajax;
			}
		} else {
			passed[ 2 ] = true;
		}
		
		checkAllValidators( passed, form_name );
	} else {
		show( sd );	
		show( 'submiter_1' );
		show( 'submiter_2' );
		sd.innerHTML = str;
	}
}

function checkAllValidators( globals, form_name ) {
	if( !inArray( globals, false ) ) {
		submitForm( form_name );
	} else {
		show( 'submiter' );
	}
}

function submitForm( form_name ) {
	document.forms[ form_name ].submit();
}


function insertTextAtCursorPos( tar, startTag, endTag, popup ) {
	if( endTag == undefined ) { endTag = ''; }
	if( popup == undefined ) { popup = false; }
	var doc = ( !popup ) ? document : window.opener.document;
	if( typeof( tar ) != 'object' ) {
		tar = doc.getElementById( tar );
	}
	if ( doc.selection ) {
		//IE 
		var sel 		= doc.selection.createRange();		
		if( sel.text != '' ) {
			// zaznaczone coś, do wstawienia
			var dupl 	= sel.duplicate();
			sel.text = startTag + dupl.text + endTag;
		} else {
			var pos = js_getCursorPosition( tar, popup );
			tar.value = tar.value.substr( 0, pos.start ) + startTag + endTag + tar.value.substr( pos.end, tar.value.length );
		}
	} else {
		// FF
		var st = tar.scrollTop;
		var startPos = tar.selectionStart;
		var endPos = tar.selectionEnd;
		var selT = tar.value.substr( startPos, endPos - startPos );
		tar.value = tar.value.substr( 0, startPos ) + startTag + selT + endTag + tar.value.substr( endPos, tar.value.length );
		tar.scrollTop = st;
	}
  //MOZILLA/NETSCAPE support
  /*
  else if (tar.selectionStart || tar.selectionStart == '0') {
    var startPos = tar.selectionStart;
    var endPos = tar.selectionEnd;
    tar.value = tar.value.substring(0, startPos)
                  + text
                  + tar.value.substring(endPos, tar.value.length);
  } else {
    myField.value += myValue;
  }
	*/
// calling the function
//insertAtCursor(document.formName.fieldName, ‘this value’);	
	/*
	if( popup == undefined ) {
		popup = false;
	}
	var pos = js_getCursorPosition( tar, popup );
	tar.value = tar.value.substr( 0, pos.start ) + text + tar.value.substr( pos.end, tar.value.length );
	tar.scrollTop = pos;
//	js_setCursorPosition( tar, pos );
*/
}

function countChars(text) {
    var n = 0;
    for (var i = 0; i < text.length; i++) {
		n++;
    }
    return n;
}

function js_CursorPos(start, end) {
    this.start = start;
    this.end = end;
}

function js_getCursorPosition( textArea, popup ) {
	if( popup == undefined ) {
		popup = false;
	}
    var start = 0;
    var end = 0;
    if ( document.selection ) { // IE…
        textArea.focus();
		var doc = ( !popup ) ? document : window.opener.document;
		var sel1 = doc.selection.createRange();
		var sel2 = sel1.duplicate();
		sel2.moveToElementText( textArea );
		var selText = sel1.text;
		var inT = "_010_";
        sel1.text = inT;
        var index = sel2.text.indexOf( inT );
        start = countChars( ( index == -1 ) ? sel2.text : sel2.text.substring( 0, index ) );
        end = countChars( selText ) + start;
        sel1.moveStart( 'character', - ( inT.length ) );
        sel1.text = selText;
    } else if ( textArea.selectionStart || ( textArea.selectionStart == "0" ) ) { // Mozilla/Netscape…
        start = textArea.selectionStart;
        end = textArea.selectionEnd;
    }
    return new js_CursorPos( start, end );
}

function js_setCursorPosition(textArea, cursorPos) {
    if (document.selection) { // IE…
        var sel = textArea.createTextRange();
        sel.collapse(true);
        sel.moveStart("character", cursorPos.start);
        sel.moveEnd("character", cursorPos.end - cursorPos.start);
        sel.select();
    } else if (textArea.selectionStart || (textArea.selectionStart == "0" )) { // Mozilla/Netscape…
        textArea.selectionStart = cursorPos.start;
        textArea.selectionEnd = cursorPos.end;
    }
    textArea.focus();
} 
