// Password checking: 2 password fields mut be equal, min 6 chars length
function passIsEqual( pass1ID, pass2ID ) {
	var pass1 =  document.getElementById( pass1ID );
	var pass2 =  document.getElementById( pass2ID );
	if( pass1.value == pass2.value ) {
		return true;
	}
	return false;
}

// Input is not empty
function isNotEmptyField( idElem ) {
	if( document.getElementById( idElem ) ) {
		if( document.getElementById( idElem ).value != "" && document.getElementById( idElem ).value != "0" ) {
			return true;
		}
		//document.getElementById( idElem ).focus();
	}
	return false;
}

// Value is higher than (integer)
function higherThan( idElem, indexInt ) {
	if( document.getElementById( idElem ) ) {
		if( document.getElementById( idElem ).value.length > indexInt ) {
			return true;
		}
		//document.getElementById( idElem ).focus();
	}
	return false;
}

// Value is equal (integer)
function equalAs( idElem, indexInt ) {
	if( document.getElementById( idElem ) ) {
		if( document.getElementById( idElem ).value.length == indexInt ) {
			return true;
		}
		//document.getElementById( idElem ).focus();
	}
	return false;
}

// Radio or checkbox is selected
function isChecked( idElem ) {
	if( document.getElementById( idElem ) ) {
		if( document.getElementById( idElem ).checked ) {
			return true;
		}
	}
	alert('Option not checked');
	return false;
}

// Radio or checkbox is selected
function isCheckedMarketing( idElem ) {
	if( document.getElementById( idElem ) ) {
		if( document.getElementById( idElem ).checked ) {
			return true;
		}
	}
	alert('You can only enter the competition if you agree with the competition terms. Please tick the checkbox underneath the form and try again.');
	return false;
}


// Valid e-mail
function isValidEmail( elem ) {
	str = document.getElementById(elem).value;
	return (str.indexOf(".") > 2) && (str.indexOf("@") > 0);
}

// Set focus on input
function setFocus( idElem ) {
	document.getElementById( idElem ).focus();
}

// Clear inputvalue
function clearValue( idElem ) {
	document.getElementById( idElem ).value = '';;
}


function setCSSChange( idElem, colorChange ) {
	//document.getElementById( idElem ).style.border = '1px solid #CC0000';;
	document.getElementById( 'l_'+idElem ).style.color = colorChange;;
}

function smartRedirect( url ) {
	if( url != "" ) {
		setTimeout( "document.location.href='"+url+"';", 2000 );
	}
}

function aHref(url) {
	document.location.href = url;
}


function getObj(name){
	if (document.getElementById) {
		this.obj = document.getElementById(name);
		this.style = document.getElementById(name).style;
	} else if (document.all) {
		this.obj = document.all[name];
		this.style = document.all[name].style;
	} else if (document.layers) {
		this.obj = document.layers[name];
		this.style = document.layers[name];
	}
}


var elementList = new Array();
var nameList 	= new Array();

function addElementToListEmpty( element, ename ) {
	elementList[elementList.length] = element;
	nameList[nameList.length] 	= ename;
}

var varErrorString = '';

function validateForm() {
	varErrorString = "";
	var myErrorArray = new Array();
	var myErrorArrayPointer = 0;
	for(var i=0;i<elementList.length;i++) {
		setCSSChange( elementList[i], "#000" );
		if( !isNotEmptyField( elementList[i] ) ) {
			varErrorString = varErrorString + 'Field "' +nameList[i]+ ' is required!\n';
			// dodaj error do listy
			myErrorArray[myErrorArrayPointer] = elementList[i];
			myErrorArrayPointer++;
		}
	}
	if( varErrorString =='' ) {
		return true;
	}
	for(var i=0;i<myErrorArrayPointer;i++) {
		setCSSChange( myErrorArray[i], "#CC0000" );
	}
	setFocus( myErrorArray[0] );
	alert("Please fill in all fileds listed below:\n"+varErrorString);
	return false;
}


var zmienionoUprawnienia = false;

function uprawnieniaZmieniono() {
	if( !zmienionoUprawnienia ) {
		pokazButtony();
	}
	zmienionoUprawnienia = true;
}

function wylaczPrzekierowanie() {
	zmienionoUprawnienia = false;
}


function pokazButtony() {
	document.getElementById('btns-1').style.display='block';
	document.getElementById('btns-2').style.display='block';
}


function sprawdzZmianyUprawnien() {
	if( zmienionoUprawnienia ) {
		//if( confirm( "Czy zapisac zmiany?" ) ) {
			//document.forms[0].submit();
			//self.location.reload();
		//}
	}
}

function isNumeric(expression) {
	var nums = "0123456789";
	if (expression.length==0)
		return false;
	for (var n=0; n < expression.length; n++)
	{
		if(nums.indexOf(expression.charAt(n))==-1)
			return false;
	}
	return true;
}


function allValidChars(email) {
  var parsed = true;
  var validchars = "abcdefghijklmnopqrstuvwxyz0123456789@.-_";
  for (var i=0; i < email.length; i++) {
var letter = email.charAt(i).toLowerCase();
if (validchars.indexOf(letter) != -1)
  continue;
parsed = false;
break;
  }
  return parsed;
}

function isValidEmail(email, required) {
if (required==undefined) {   // if not specified, assume it's required
required=true;
}
if (email==null) {
if (required) {
return false;
}
return true;
}
if (email.length==0) {  
if (required) {
return false;
}
return true;
}
if (! allValidChars(email)) {  // check to make sure all characters are valid
return false;
}
if (email.indexOf("@") < 1) { //  must contain @, and it must not be the first character
return false;
} else if (email.lastIndexOf(".") <= email.indexOf("@")) {  // last dot must be after the @
return false;
} else if (email.indexOf("@") == email.length) {  // @ must not be the last character
return false;
} else if (email.indexOf("..") >=0) { // two periods in a row is not valid
	return false;
} else if (email.indexOf(".") == email.length) {  // . must not be the last character
	return false;
}
return true;
}

function scrollAnswer( answerID ) {
document.getElementById('answer_'+answerID).style.display = "block";
}
function hideAnswer( answerID ) {
document.getElementById('answer_'+answerID).style.display = "none";
}

function scrollWinners( winnerID ) {
document.getElementById('winners_'+winnerID).style.display = "block";
}
function hideWinners( winnerID ) {
document.getElementById('winners_'+winnerID).style.display = "none";
}

function clickBrowseFile(pic)
{
document.getElementById(pic).click();
}

var pic_input = 2;
function ViewNextPicInputs()
{
	if (pic_input < 5)
	{
		document.getElementById('pic_inputs-'+pic_input).style.display = "block";
		pic_input++;
	}
	else
	{
		document.getElementById('pic_inputs-5').style.display = "block";
		document.getElementById('morePictures').style.display = "none";
	}
}

function galeria( img, w, h ){
	opcje = "height="+ h +",width="+ w +",scrollbars=no,resizable=no,menubar=no";
	w = window.open("/img.php?img=" + img, "", opcje, true);
	w.focus ();
}



/* FORUM */

function forumGaleria( tematID, imgID ) {
	newwindow=window.open( '/forum/galeria/' + tematID +'.html?img='+imgID, 'forum_img', 'height=700,width=780,scrollbars=auto,resizable=yes,menubar=no,top=0,left=0' )
	if (window.focus) {newwindow.focus()}
	return false;
}

function forumUser( userID ) {
	newwindow=window.open( '/forum/user/' + userID +'.html', 'forum_img', 'height=200,width=400,scrollbars=auto,resizable=yes,menubar=no,top=0,left=0' )
	if (window.focus) {newwindow.focus()}
	return false;
}



function startForumTimeout() {
	setTimeout( "getBacLocation()", 2000 );
}


function getBacLocation() {
	history.back();
	//document.location.reload();
}


var previewFields = new Array();

function showPreview( template ) {
	newwindow=window.open( '/templates/popup/'+template,'preview','height=500,width=520,scrollbars=yes');
	if (window.focus) {newwindow.focus()};
}


function performShow() {
	for( var i=0; previewFields[i]; i++ ) {
		var source = document.getElementById( previewFields[i] );
		if( source ) {
			var dest = newwindow.document.getElementById( previewFields[i]+"_add" );
			dest.innerHTML = source.value;
		}
	}
}



/* AJAX */


var actualLink;
var actualContainer;

function loadAjaxPage( linkURL, containerID ) {
	actualLink = linkURL;
	actualContainer = containerID;
	jQuery.ajax({
		url: linkURL,
		success: function(msg){
			jQuery("#"+containerID).html( msg );
		}
	});
}

function loadAjaxJSPage( linkURL, containerID ) {
	actualLink = linkURL;
	actualContainer = containerID;
	jQuery.ajax({
		url: linkURL,
		dataType: "html",
		success: function(msg){
			if( msg.length > 0 ) {
				jQuery("#"+containerID).html( msg );
			}
		}
	});
}

function reloadPage( pageNum ) {
	advAJAX.get({
		  url: actualLink+'?strona='+pageNum,
		  onSuccess : function(obj) { if( obj.responseText.length > 1 ) {  document.getElementById(actualContainer).innerHTML = obj.responseText; } }
	});
}


function nl2br( str ) {
	if(typeof(str)=="string") return str.replace(/\\n/g,"<BR>");
	else return str;
}


function displayLoginBox(){
	//if (showLoginBox == 0){
		jQuery("#logowanie").css("display", "block");
		showLoginBox = 1;
	//} else {
	//	jQuery("#logowanie").css("display", "none");
	//	showLoginBox = 0;
	//}
}

function checkUnique(table, field, name, edit){
	var elem = jQuery("#"+field).val();
	if (elem.length == 0){
		alert ('Aby sprawdzić unikalność pole musi być wypełnione!');
		return false;
	}
	loadAjaxPage('/ajax/check_unique.html?table='+table+'&field='+field+'&name='+name+'&elem='+elem+'&edit='+edit, field+'-unique_info');
}


function quotePost(post){
	var tresc = jQuery("#comment-text").val();
		jQuery.ajax({
		   type: "POST",
		   dataType: "html",
		   url: '/ajax/quote_post.html?post='+post,
		   data: "tresc="+tresc,
		   success: function(msg){
		     jQuery("#comment-text").val(msg);
		     jQuery("#okienko").css("display", "block");
		   }
		});
}


function showCommentBox(){
	jQuery("#popup-mail").css("display", "none");
	jQuery("#okno-galeria").css("display", "none");	
	jQuery("#okienko").css("display", "block");
}

function hideCommentBox(){
	jQuery("#okienko").css("display", "none");
}

function showMailToFriend(){
	jQuery("#okienko").css("display", "none");
	jQuery("#okno-galeria").css("display", "none");
	jQuery("#popup-mail").css("display", "block");
}

function hideMailToFriend(){
	jQuery("#popup-mail").innerHTML = "sent-info";
	jQuery("#popup-mail").css("display", "none");
}

function showGalleryBox(){
	jQuery("#popup-mail").css("display", "none");	
	jQuery("#okienko").css("display", "none");
	jQuery("#okno-galeria").css("display", "block");
}

function hideGalleryBox(){
	jQuery("#okno-galeria").css("display", "none");
}

function showWydarzenie(id) {
	for (var i=0; i<5; i++){
		if (id == i){
			jQuery("#plus-"+i).css("display","none");	
			jQuery("#minus-"+i).css("display", "block");
		} else {
			jQuery("#plus-"+i).css("display","block");	
			jQuery("#minus-"+i).css("display", "none");
		}
	}
}

function hideWydarzenie(id){
	jQuery("#plus-"+id).css("display", "block");
	jQuery("#minus-"+id).css("display", "none");
}

function showKomentarz(id) {
	for (var i=0; i<5; i++){
		if (id == i){
			jQuery("#kplus-"+i).css("display","none");	
			jQuery("#kminus-"+i).css("display", "block");
		} else {
			jQuery("#kplus-"+i).css("display","block");	
			jQuery("#kminus-"+i).css("display", "none");
		}
	}
}

function hideKomentarz(id){
	jQuery("#kplus-"+id).css("display", "block");
	jQuery("#kminus-"+id).css("display", "none");
}

function rozwinListe(id) {
	for (var i=0; i<iloscList; i++){
		if (id == i){
			jQuery("#lplus-"+i).css("display","none");	
			jQuery("#lminus-"+i).css("display", "block");
		} else {
			jQuery("#lplus-"+i).css("display","block");	
			jQuery("#lminus-"+i).css("display", "none");
		}
	}
}


function sendMailToFriend() {
	var link = jQuery("#form-link").val();
	var yourName = jQuery("#form-your_name").val();
	var token = jQuery("#form-token").val();
	var yourEmail = jQuery("#form-your_email").val();
	var friendEmail = jQuery("#form-friend_email").val();
	var message = jQuery("#form-message").val();
	
	if (yourEmail != '' && !isValidEmail(yourEmail))
	{
		yourEmail = 'error';
	}
	if (friendEmail != '' && !isValidEmail(friendEmail))
	{
		friendEmail = 'error';
	}
   jQuery.ajax({
   type: "POST",
		   url:  '/ajax/send_mail_fo_friend.html',
		   dataType: "html",
		   data:  "link="+link+"&yourName="+yourName+"&token="+token+"&yourEmail="+yourEmail+"&friendEmail="+friendEmail+"&message="+message,
		   success: function(msg){
			 jQuery("#popup-mail").html(msg);
		   }
});
return;
}

function showListaObecnosci(id_materialu, show){
	loadAjaxPage('/ajax/lista_obecnosci.html?id_materialu='+id_materialu+'&show='+show, 'ajax-lista');
}

function zapiszListaObecnosci(id_materialu, user){
	loadAjaxPage('/ajax/lista_obecnosci.html?zapisz&id_materialu='+id_materialu+'&user='+user+'&show=1', 'ajax-lista');
}

function wypiszListaObecnosci(id_materialu, user){
	loadAjaxPage('/ajax/lista_obecnosci.html?wypisz&id_materialu='+id_materialu+'&user='+user+'&show=1', 'ajax-lista');
}

function showBioraUdzial(id_materialu, show){
	loadAjaxPage('/ajax/biora_udzial.html?id_materialu='+id_materialu+'&show='+show, 'ajax-lista');
}

function zapiszBioraUdzial(id_materialu, user){
	loadAjaxPage('/ajax/biora_udzial.html?zapisz&id_materialu='+id_materialu+'&user='+user+'&show=1', 'ajax-lista');
}

function wypiszBioraUdzial(id_materialu, user){
	loadAjaxPage('/ajax/biora_udzial.html?wypisz&id_materialu='+id_materialu+'&user='+user+'&show=1', 'ajax-lista');
}

function showZdjecie(element){
	loadAjaxPage('/ajax/najnowsze_zdjecia.html?element='+element, 'ajax-zdjecia');
}

function changePolecamy(id){
	jQuery("#main_news").css( "background", "url(/upload/polecamy/"+back[id]+") 10px 4px no-repeat" );
	for (var i=1; i<=3; i++){
		if (i == id){	
			document.getElementById('polecamy_'+i).className = "hovered";
		} else {	
			document.getElementById('polecamy_'+i).className = "unhovered";	
		}
	}
}

function showRegulamin( konkurs ) {
	newwindow=window.open( '/popup/regulamin/'+konkurs+'.html','preview','height=400,width=500,scrollbars=yes');
	if (window.focus) {newwindow.focus()};
}

var selectedGalleries = new Array();

function selectAllPictures(galeria, ilosc) {
	if (selectedGalleries[galeria] == 0){
		var val = true;
		selectedGalleries[galeria] = 1;	
		document.getElementById('select-button'+galeria).value = 'Odznacz wszystkie';
	} else {
		var val = false;
		selectedGalleries[galeria] = 0;	
		document.getElementById('select-button'+galeria).value = 'Zaznacz wszystkie';
	}
	for (var i=0; i<ilosc; i++){
			document.getElementById('del_foto-'+galeria+'_'+i).checked = val;
	}
}

function submitDelete(question) {
	if( confirm( question ) ) {
		return true;
	} else {
		return false;
	}
}

function clearWydarzeniaLinks() {
	jQuery("#wydarzenia-box .item-off h6 a").unbind( "click" );
	jQuery("#wydarzenia-box .item-on h6 a").click(function (e) {
		document.location.href = jQuery("#wydarzenia-box .item-on h6 a").attr("href");
	});
}
function clearKomentarzeLinks() {
	jQuery("#komentarze-box .item-off h6 a").unbind( "click" );
	jQuery("#komentarze-box .item-on h6 a").click(function (e) {
		document.location.href = jQuery("#komentarze-box .item-on h6 a").attr("href");
	});
}

function clearLastUsersLinks() {
	jQuery("#last_users-box .item-off h6 a").unbind( "click" );
	jQuery("#last_users-box .item-on h6 a").click(function (e) {
		document.location.href = jQuery("#last_users-box .item-on h6 a").attr("href");
	});
}

var selectedMessages = 0;

function selectAllMessages(c) {
	if (selectedMessages == 0){
		var val = true;
		selectedMessages = 1;	
		jQuery("#select-button").val("Odznacz wszystkie");
	} else {
		var val = false;
		selectedMessages = 0;	
		jQuery("#select-button").val("Zaznacz wszystkie");
	}
	for (var i=1; i<=c; i++){
			document.getElementById('del_message-'+i).checked = val;
	}
}

var flags = new Array();

function showMessage(id, flag){
	jQuery.ajax({
		url: '/ajax/pokaz_wiadomosc.html?message='+id+'&box=1',
		success: function(msg){
			jQuery("#ajax-message").html( msg );
			var new_messages = jQuery("#new-messages").html();
			if (flags[id] != 1 && flag == 1){
				new_messages--;
				flags[id] = 1;
				if (new_messages == 0){
					document.getElementById('mail-belka').className = "mail-old";
					new_messages = "0";
				} 
				jQuery("#new-messages").html(new_messages);
				document.getElementById('img-'+id).src = "/i/inbox/2.gif";
			}
			document.getElementById('tr-'+id).className = "ac";
		}
	});
}

function showOutboxMessage(id){
	jQuery.ajax({
		url: '/ajax/pokaz_wiadomosc.html?message='+id+'&box=2',
		success: function(msg){
			jQuery("#ajax-message").html( msg );
			document.getElementById('tr-'+id).className = "ac";
		}
	});
}

var AcceptStatus = 0;

function setAcceptStatus(status){
	AcceptStatus = status;
}
function submitClick(question_1, question_2) {
	
	if (AcceptStatus == 1){
		question = question_1;
	} else {
		question = question_2;
	}
	
	if( confirm( question ) ) {
		document.getElementById('action-input').value = AcceptStatus;
		return true;
	} else {
		return false;
	}
}


var selectedFriends = 0;

function selectAllFriends(c) {
	if (selectedFriends == 0){
		var val = true;
		selectedFriends = 1;	
		jQuery("#select-button").val("Odznacz wszystkie");
	} else {
		var val = false;
		selectedFriends = 0;	
		jQuery("#select-button").val("Zaznacz wszystkie");
	}
	for (var i=1; i<=c; i++){
			document.getElementById('del_friend-'+i).checked = val;
	}
}

var selectedInvites = 0;

function selectAllInvites(c) {
	if (selectedInvites == 0){
		var val = true;
		selectedInvites = 1;	
		jQuery("#select-button2").val("Odznacz wszystkie");
	} else {
		var val = false;
		selectedInvites = 0;	
		jQuery("#select-button2").val("Zaznacz wszystkie");
	}
	for (var i=1; i<=c; i++){
			document.getElementById('del_invite-'+i).checked = val;
	}
}

var selectedClickInvites = 0;

function selectAllClickInvites(c) {
	if (selectedClickInvites == 0){
		var val = true;
		selectedClickInvites = 1;	
		jQuery("#select-button3").val("Odznacz wszystkie");
	} else {
		var val = false;
		selectedClickInvites = 0;	
		jQuery("#select-button3").val("Zaznacz wszystkie");
	}
	for (var i=1; i<=c; i++){
			document.getElementById('click_invite-'+i).checked = val;
	}
}

var selectedFound = 0;

function selectAllFound(c) {
	if (selectedFound == 0){
		var val = true;
		selectedFound = 1;	
		jQuery("#select-button4").val("Odznacz wszystkie");
	} else {
		var val = false;
		selectedFound = 0;	
		jQuery("#select-button4").val("Zaznacz wszystkie");
	}
	for (var i=1; i<=c; i++){
			document.getElementById('invite_friend-'+i).checked = val;
	}
}

function doInviteSearch() {
	var phrase = document.getElementById('phrase').value;
	if (phrase != ''){
		loadAjaxPage('/ajax/zapros_znajomych.html?sent&phrase='+phrase, 'ajax-invite');
	} else {
		alert('You have to write a phrase!');
	}
}

function inviteUser( user ) {
	loadAjaxPage('/ajax/zapros_uzytkownika.html?user='+user, 'ajax-invite');
}

function hidePopup(){
	jQuery("#ajax_popup").css("display", "none");
}

var canSubmit = true;

function checkInterval(pole, error, min, max) {

	var field_od = document.getElementById(pole+'_od').value;
	var field_do = document.getElementById(pole+'_do').value;
	switch (true){
		case field_od == "" && field_do != "" && (!isNumeric(field_do) || parseInt(field_do) < min || parseInt(field_do) > max):
			document.getElementById(pole+'_info').innerHTML = error;
			canSubmit = false;
		break;
		case field_od != "" && field_do == "" && (!isNumeric(field_od) || parseInt(field_od) < min || parseInt(field_od) > max):
			document.getElementById(pole+'_info').innerHTML = error;
			canSubmit = false;
		break;
		case field_od != "" && field_do != "" && (!isNumeric(field_od) || !isNumeric(field_do) || parseInt(field_od) < min || parseInt(field_do) < min || parseInt(field_od) > max || parseInt(field_do) > max || parseInt(field_do) < parseInt(field_od)):
			document.getElementById(pole+'_info').innerHTML = error;
			canSubmit = false;
		break;
		default:
			document.getElementById(pole+'_info').innerHTML = '';
			canSubmit = true;
		break;
	}

}

function submitSzukaj(error) {
	if (canSubmit == false){
		alert(error);
		return false;
	} else {
		return true;
	}
}
