/* usefull util functions */

function checkSubmitSearch() {
	var linker = '/szukaj/'+document.getElementById('search_word').value;
	window.location.href = linker;
}

function enterPressed(evn) {
	if (window.event && window.event.keyCode == 13) {
	  checkSubmitSearch();
	} else if (evn && evn.keyCode == 13) {
	  checkSubmitSearch();
	}
}


function putHtml( id, str ) {
	var h = ( typeof( id ) == 'object' ) ? id : get( id );
	h.innerHTML = str;
}

function getSelected(opt) {
	var selected = new Array();
	var index = 0;
	for (var intLoop=0; intLoop < opt.length; intLoop++) {
		if ( opt[ intLoop ].selected ) {
			index = selected.length;
			selected[ index ] = new Object;
			selected[ index ].value = opt[ intLoop ].value;
			selected[ index ].index = intLoop;
	 }
  }
  return selected[ index ];
}

function addEvent(obj, type, fn){
	if (obj.addEventListener) {
		obj.addEventListener(type, fn, false);
	}
	else if (obj.attachEvent) {
		obj['e'+type+fn] = fn;
		obj[type+fn] = function() { obj['e'+type+fn](window.event); }
		obj.attachEvent('on'+type, obj[type+fn]);
	}
}

function checkNumber(e)
{
	var numbers = '0123456789- ';
	var key     = window.event ? window.event.keyCode : e ? e.which : null;
	var keychar = String.fromCharCode(key);
	return ( numbers.indexOf(keychar)!=-1 || key==null || key==0 || key==8 || key==9 || key==13 || key==27 );
}

function validateNumber(e){
	var numbers = new RegExp( "^[0-9]+$" );
	return numbers.test( e );
}

function clearLogin( id ) {
	switch( id ) {
		case 'public_login':
			if( trim( getValue( id ) ) == 'adres e-mail' ) {
				get( id ).value = '';
			}
			break;
		case 'public_password':
			if( trim( getValue( id ) ) == 'hasło' ) {
				get( id ).value = '';
			}
			break;
	}
}

function fillLogin( id ) {
	switch( id ) {
		case 'public_login':
			if( trim( getValue( id ) ) == '' ) {
				get( id ).value = 'adres e-mail';
			}
			break;
		case 'public_password':
			if( trim( getValue( id ) ) == '' ) {
				get( id ).value = 'hasło';
			}
			break;
	}
}


function get( id ) {
	return document.getElementById( id );
}

function getValue( str ) {
	var st = get( str );
	if( st != null ) {
		return trim( st.value );
	} else {
		return ' ';
	}
}


function swapHashCode() {
	var h		= get( 'hashcode' );
	h.value = 'foto';
}

function hide( str ) {
	var h = ( typeof( str ) == 'object' ) ? str : get( str );
	if( h != undefined ) {
		h.style.display = "none";
	} else {
//		alert( 'błąd (hide)' );
	}
}

function show( str ) {
	var h = ( typeof( str ) == 'object' ) ? str : get( str );
	if( h != undefined ) {
		h.style.display = "block";
	}
}

function changeVisible( str ) {
	var h = ( typeof( str ) == 'object' ) ? str : get( str );
	if( h != undefined ) {
		if( h.style.display == 'none' ) {
			h.style.display = 'block';
		} else {
			h.style.display = 'none';
		}
	} else {
		alert( 'błąd (changeVisible)' );
	}
}

function trimLeft( s ) {
	while( s.substring( 0, 1 ) == " " ){
		s = s.substr( 1 );
	}
	return s;
}

function inArray( array, id ) {
	for( i in array ) {
			if( array[ i ]  == id ) {
					return true;
			}
	}
	return false;
}

function indexOfArray( array, id ) {
	for( i in array ) {
			if( array[ i ]  == id ) {
					return i;
			}
	}
	return -1;
}

function trimRight( s ) {
	while( s.charAt( s.length - 1 ) == " " ) {
		s = s.substr( 0, s.length - 1 );
	}
	return s;
}

function trim( s ) {
	s = trimLeft( s );
	s = trimRight( s );
	return s;
}

/*BKR - do ankiety */
function fillFromChecklist(element,limit,question) {


	var position, value, br, pos;
	var chbxy = new Array();
	var text_id = "l"+element.id;
	value = element.value;
	pos = element.id.indexOf('_q');
	pos = element.id.substring(pos);
	var el_lab = document.getElementById(text_id);
	var v_text = document.getElementById(text_id).innerHTML;

	if (limit == 0) {
		if(element.checked) {
			el_lab.className = "checkbox_checked";
		}
		else if (element.checked == false) {
			el_lab.className = "checkbox_unchecked";
		}
		return false;
	}

	if(element.checked) {
		for(i=1;i<=limit;i++) {
			position = document.getElementById('pozycja'+i+'_q'+question);
			if(position.innerHTML == '' || position.innerHTML == undefined) {
				//position.innerHTML = value;
				position.innerHTML = v_text;
				i = eval(limit+"+"+1);
			}
		}
		el_lab.className = "checkbox_checked";
	}
	else {
		for(i=1;i<=limit;i++) {
			position = document.getElementById('pozycja'+i+'_q'+question);
			//if(position.innerHTML == value) {
			if(position.innerHTML == v_text) {

				position.innerHTML = '';
				i = eval(limit+"+"+1);
			}
		}
		el_lab.className = "checkbox_unchecked";
	}
	checkowane = 0;
	chbxy = document.getElementsByTagName('input');
	for(i=1;i<=limit;i++) {
		position = document.getElementById('pozycja'+i+'_q'+question);
		if(position.innerHTML == '' || position.innerHTML == undefined) {	}
		else {
			checkowane++;
		}
	}

	for(i=0;i<chbxy.length;i++) {
		if(chbxy[i].type == 'checkbox' && chbxy[i].id.substring(chbxy[i].id.indexOf('_q')) == pos) {
			if(!(chbxy[i].checked)) {
				if(checkowane == limit) {
					chbxy[i].disabled = true;
				}
				else {
					chbxy[i].disabled = false;
				}
			}
		}
	}

	document.getElementById('pusty_a').click();
}

function znaki(textar, liczba) {
	if(liczba == '') { liczba = 350;}
	var ilosc = (liczba - textar.value.length);
	if(ilosc < 0) {
		textar.value = textar.value.substring(0,liczba);
		ilosc = 0;
	}
	//if(div == '') { div ='znaczki';	}
	//document.getElementById(div).innerHTML = ilosc;
}

function karta_skarbonka(element,element_text) {
	if(element.checked) {
		element_text.readonly = false;
	}
	if(element.checked == false) {
		element_text.readonly = true;
	}
}

function valid() {
	var form = document.getElementById('forma');
	var fake = 1;
	var faked = 0;
	var faking = new Array();
	for(i=0;i<form.length;i++) {
		if(form[i].tagName.toUpperCase() == 'INPUT' && form[i].name.substr(0,1) == 'v' && form[i].value == '1' ) {
			var qid = form[i].name.substring(1);
			faking[qid] = 1;
			for(ii=0;ii<form.length;ii++) {
				var re = new RegExp("(a[0-9]*)?_q"+qid+"$", "g");

				if(form[ii].name.match(re) != null ) {
					//alert(form[ii].type);
					switch(form[ii].type) {
						case 'radio':
							if (form[ii].checked == true) {
								faking[qid] = 0;
							}
							break;
						case 'checkbox':
							if (form[ii].checked == true) {
								faking[qid] = 0;
							}
							break;
						case 'text':
							if (form[ii].value != '') {
								faking[qid] = 0;
							}
							break;
					}
				}
			}
			if(faking[qid] == 1) {	faked++;	}
		}
	}
	if(faked > 0) {
		alert("Jedno z pytań jest wymagane.\nProszę wypełnić/zaznaczyć wymagane pola!")
		return false;
	}
	return true;
}
function tryAddComment(a, b){
	var t = getValue( 'comment-text' );
	var u = getValue('comment-user');
	if( t == '' )alert("Nie wpisano treści komentarza");
	else if(u == '')alert("Nie wpisano autora komentarza");
	else{
		var ajax = new myAjax();
		ajax.action = 'tryAddComment';
		ajax.post( 't='+t+'&u='+u+'&obj='+a+'&id='+b );
		ajax.onLoad = function() {
			switch( this.response ) {
				case 'ok':
					document.location.reload();
					break;
				default:
					alert( this.response );
					break;
			}
		}
	}
}

function wyloguj(){
		var ajax = new myAjax();
		ajax.action = 'logout';
		ajax.post( 'ghj=sd' );
		ajax.onLoad = function() {
			switch( this.response ) {
				case 'ok':
					document.location.reload();
					break;
				default:
					alert( this.response );
					break;
			}
		}
}
function delete_item(user,id){
	if(confirm('Czy napewno chcesz usunąć wpis??')){
		document.location='/blog/'+user+'/action/delete/id/'+id;//+'/data/'+data+'/strona/'+strona;
	}
}
function strona1(id, a, ile){
	if(a==0){
		a=activ_strona+1;
	}
	else if(a==-1){
		a=activ_strona-1;
	}
	for(var i=1;i<=ile;i++){
		if(i==a)document.getElementById(id+'-s'+a).style.display='block';
		else {
			document.getElementById(id+'-s'+i).style.display='none';
		}
	}
	
	if(a==1)document.getElementById(id+'-pop').innerHTML='';
	else document.getElementById(id+'-pop').innerHTML='<a onclick="strona(\''+id+'\', '+(a-1)+');" href="javascript:void(0);">«</a>';
	
	if(a<ile)document.getElementById(id+'-nas').innerHTML='<a onclick="strona(\''+id+'\', '+(a+1)+');" href="javascript:void(0);">»</a>';
	else document.getElementById(id+'-nas').innerHTML='';
	
	document.getElementById(id+'-strony').innerHTML='Strona ' + a + '/' + ile ;
	activ_strona=a;	
}

function tryLogin( t, u){
	//var t = getValue( 'login_reg' );
	//var u = getValue('pass_reg');
        //var r = getValue('referer_reg');
        //alert( login+'     '+pass+'      '+referer);
	if( t == '' )alert("Nie wpisano loginu");
	else if(u == '')alert("Nie wpisano hasła");
	else{
		var ajax = new myAjax();
		ajax.action = 'publicLogin';
		ajax.post( 'cn=People&login='+t+'&pass='+u );
		ajax.onLoad = function() {
                        var response = this.response;
                        var splitter = response.indexOf("|");
                        var response1 = response.substr(1,splitter-1);
                        var response2 = response.substr(splitter,response.length);
                        //alert(response);
                        //alert(splitter);
                        //alert(response1);
                        //alert(response2);
                        if (response1 =='ok'){
                                switch( response2 ) {
                                        case '|':
                                                //forum_login();
                                                document.location.reload(true);
                                                break;
                                        default:
                                        var link = response2.substr(1,response2.length);
                                                window.location.replace(link);
                                                break;
                                }
                        }
                        
		}
	}
}


function forum_login(username, password) {
	//var form	= get( 'login_form_reg' );
	//var username	= form.login_reg.value;
	//var password	= form.pass_reg.value;
	var login	= 'zaloguj';
	var redirect	= '/forum/';
	
	var ajax = new myAjax();
		ajax.action = 'forum_login';
		ajax.uri = '/forum/ucp.php?mode=login';
		ajax.post( 'password='+password+'&username=' + username+'&redirect=' + redirect+'&login=' + login );
		ajax.onLoad = function( text ) {
			get( 'sidd' ).value = text;
			//submit_form( 'login_form' );
		}
		
}

function submit_form( form ) {
	var elems = get( form ).childNodes;
	var label;
	var names = "";
	
	for( i=0; i<elems.length; i++ ) {
		var tag = elems[i].tagName;
		var el_id = elems[i].id;
		if( tag ) {
			if( tag.toLowerCase() == 'input' || tag.toLowerCase() == 'select') {
				label = get( 'label_' + el_id );
				if( label ) {
					label_txt = label.innerHTML;
					names += el_id+'|'+label_txt+'|';
				}
				if( el_id == 'regulamin' ) names += el_id+'|Regulamin|';
				if( el_id == 'przetwarzanie' ) names += el_id+'|Zgoda na przetwarzenie|';
			}
		}
	}
	if( validateMe( form, names ) ) {
		document.getElementById( form ).submit();
	}
}

function validateMe( form, names ) {
	var names_array = names.split( '|' );
	var text = "Błędy w formularzu:\n\n";
	var falsed = false;
	
	for( i = 0; i < names_array.length - 1; i += 2 ) {
		var elem = dget( names_array[ i ] );
		if( trim( elem.value ) == '' ) {	text += names_array[ i + 1 ]+" - puste pole\n";	falsed = true;	}
		if( elem.id == 'regulamin' )
			if( !elem.checked )
				{	text += names_array[ i + 1 ]+" - nie zaznaczony\n";	falsed = true;	}
		if( elem.id == 'przetwarzanie' )
			if( !elem.checked )
				{	text += names_array[ i + 1 ]+" - nie zaznaczony\n";	falsed = true;	}
	}
	
	if( falsed ) {
		alert( text );
		return false;
	}
	
	return true;
}

function forum_logout() {
        
	var ajax = new myAjax();
		ajax.action = 'forum_logout';
		ajax.uri = '/forum/ucp.php?mode=logout2';
		ajax.onLoad = function( text ) {
			window.location = "/module/logout/";
		}
		ajax.post( "nic=nic");
}

function test_wiedzy() {
        var form = $("#test-wiedzy");
        for( i=1; i<11; i++ ) {
                var elem = $("input[@name=radio_group_"+i+"]:checked").val();
                if (elem==undefined){
                        alert ("wypełnij pozycję nr"+i)
                        return false;
                }
        }
        form.submit();
}

function clearInput( id ) {
	switch( id ) {
		case 'n_email':
			if( trim( getValue( id ) ) == 'Twój adres e-mail' ) {
				get( id ).value = '';
			}
			break;
		case 'login':
			if( trim( getValue( id ) ) == 'login' ) {
				get( id ).value = '';
                $('#passtext').css("display","none");
                $('#pass').css("display","block");
			}
			break;
		case 'pass':
			//if( trim( getValue( id ) ) == 'hasło' ) {
                
				//get( id ).type = 'password';
				//get( id ).value = '';
			//}
			break;
	}
}

function fillInput( id ) {
	switch( id ) {
		case 'n_email':
			if( trim( getValue( id ) ) == '' ) {
				get( id ).value = 'Twój adres e-mail';
			}
			break;
		case 'login':
			if( trim( getValue( id ) ) == '' ) {
				get( id ).value = 'login';
                $('#passtext').css("display","block");
                $('#pass').css("display","none");
			}
			break;
		case 'pass':
			//if( trim( getValue( id ) ) == '' ) {
                

				//get( id ).type = 'text';
				//get( id ).value = 'hasło';
			//}
			break;
	}
}

var redir = '';

function publicLogin() {
	var l 	= getValue( 'login' );
	var p	= getValue( 'pass' );

	get( 'pl_error' ).innerHTML = '';
	get( 'pl_error' ).style.display = 'none';

	var ajax = new myAjax();
	var pstr = 'login='+l+'&pass='+p+'&cn=People';
	ajax.action = 'publicLogin';

	ajax.post ( pstr );
	ajax.onLoad = function() {
		if( trim( this.response ) == 'ok' ) {
			publicForumLogin( l, p );
		}
		else {
			alert( this.response );
		}

	}
}

function publicLoginRegister() {
	var l 	= getValue( 'login_reg' );
	var p	= getValue( 'pass_reg' );

	get( 'pl_error' ).innerHTML = '';
	get( 'pl_error' ).style.display = 'none';

	var ajax = new myAjax();
	var pstr = 'login='+l+'&pass='+p+'&cn=People';
	ajax.action = 'publicLogin';

	ajax.post ( pstr );
	ajax.onLoad = function() {
		if( trim( this.response ) == 'ok' ) {
			publicForumLogin( l, p );
		}
		else {
			alert( this.response );
		}

	}
}

function publicForumLogin( l, p ) {
	var ajax = new myAjax();
	var posty = 'login=yes&username='+l+'&password='+p;
	ajax.uri = "/forum/ucp.php?mode=ajax_login";
	//ajax.action = '';
	ajax.post( posty );
	ajax.onLoad = function() {
		var ar = this.response;
		var ae = new Array();
		ae = ar.split( '|' );
		if( trim( ae[0] ) == 'ok' ){
			saveSession( ae[1] );
		}
		else {
			alert( 'Wpisano błędny login i/lub hasło.Spróbuj jeszcze raz' );
			ajax_logout();
		}
	}
}

function ajax_logout() {
	var ajax = new myAjax();
	ajax.uri = '/module/logout';
	ajax.post( '' );
	ajax.onLoad = function() {
		deleteSession();
	}
}


function saveSession( session ){
	if( session != undefined ){
		var ajax = new myAjax();
		ajax.action = 'saveSession';
		var posty = 'session='+session;
		ajax.post( posty );
		ajax.onLoad = function() {
			if( trim( this.response ) == 'ok' ){
				if( redir != '' && redir != undefined )
					var ol = redir;
				else
					var ol = window.location;

				window.location = ol;
			}
			else {
				alert( 'Błąd logowania.Odwież stronę i sprobuj ponownie' );
				ajax_logout();
			}
		}
	}
	else {
		alert( 'Błąd logowania.Odwież stronę i sprobuj ponownie' );
		ajax_logout();
	}
}

function deleteSession( ){
	var ajax = new myAjax();
	ajax.action = 'delSession';
	var posty = '';
	ajax.post( posty );
	ajax.onLoad = function() {
		if( trim( this.response ) == 'ok' ){
			var ol = window.location;
			window.location = ol;
		}
		else {
			alert( 'Błąd wylogowania.Odwież stronę i sprobuj ponownie' );
		}
	}
}

function getNoteSrc( id, note ) {
	var tmp = '/images/grade-star-ZERO.png';
	if( ( id <= note ) && ( note - id != -0.5 ) ) {
		return tmp.replace( 'ZERO', 'full' );
	} else if( note - id == -0.5 ) {
		return tmp.replace( 'ZERO', 'half' );
	} else {
		return tmp.replace( 'ZERO', 'empty' );
	}
}

function triggerNotes( id, note ) {
	for( i = 1; i <= 5; i++ ) {
		var img = get( 'note_'+i.toString() );
		if( id >= i ) {
			img.src = getNoteSrc( i, 5 );
			get ('opinion-value').value = i;
		} else {
			img.src = getNoteSrc( i, 0 );
		}
	}
}

function detriggerNotes( id, note ) {
	for( i = 1; i <= 5; i++ ) {
		var img = get( 'note_'+i.toString() );
		img.src = getNoteSrc( i, note );
	}	
}

function reload(city){
	window.location = "/konkurs/city/"+city;
}