// 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;
		}
	}
	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 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 changeCategory() {
	var select = document.getElementById('subject-select').value;
	if (select != "") {
	document.location.href='/life_in/ask_expert_list/'+select+'.html';
	return;
	}
	alert ('You have to select a subject!');
}

function selectExpert() {
	var select = document.getElementById('expert-select').value;
	if (select != "") {
	document.location.href='/life_in/ask_expert/'+select+'.html';
	return;
	}
	alert ('You have to select an expert!');
}

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";
}



/* 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 = $("#"+previewFields[i]).val();
		source = source.replace(/\n/g, '<br />');
		if( newwindow ) {
			var dest = newwindow.document.getElementById( previewFields[i]+"_add" );
			dest.innerHTML = source;
		}
	}
}



/* AJAX */


var actualLink;
var actualContainer;

function loadAjaxPage( linkURL, containerID ) {
	actualLink = linkURL;
	actualContainer = containerID;
	advAJAX.get({
		  url: linkURL,
		  onSuccess : function(obj) { if( obj.responseText.length > 1 ) {  document.getElementById(containerID).innerHTML = obj.responseText; } }
	});
}

function reloadPage( pageNum ) {
	advAJAX.get({
		  url: actualLink+'?strona='+pageNum,
		  onSuccess : function(obj) { if( obj.responseText.length > 1 ) {  document.getElementById(actualContainer).innerHTML = obj.responseText; } }
	});
}


function saveEntryAsStatus( status ) {
	switch( status ) {
		case 1:
			// dont confirm
			break;
		case 2:
			if( !confirm( 'Are you sure you want to AWAIT PUBLISH this article?' ) ) {
				return false;
			}
			break;
		case 3:
			if( !confirm( 'Are you sure you want to save this article as DRAFT?' ) ) {
				return false;
			}		
			break;
		case 4:
			if( !confirm( 'Are you sure you want to DEPUBLISH this article??' ) ) {
				return false;
			}		
			break;
	}
	// call me the traditionalist
	var input = document.getElementById('status-change');
	if( typeof( input ) != "undefined" ) {
		input.value = status;
	}
	document.forms[0].submit();
}

function deleteElement( question, link, id ) {
	if( confirm( question ) ) {
		document.location.href=link+id;
	}
}

function deleteElementAjax( question, link, id ) {
	if( confirm( question ) ) {
		loadAjaxPage( '/index.php'+link+id, 'our-table' );
	}
}


function deleteCheckedInputs() {
		var values = "";
		var table = $('table.listing');
		var checks = table.find('input[@type="checkbox"]');
		for( var i=0; checks[i]; i++ ) {
			if( checks[i].checked == true ) {
				values = values+":"+checks[i].value;
			}
		}
		loadAjaxPage( '/index.php?module={$options.panel}'+panelID+'&mass_delete_string='+values, 'our-table' );
}





var allowRewriteURL= true;

function rewriteURL( string, destinationID ) {
	if( allowRewriteURL ) {
		var newstring = "";
		for( var i=0; i<string.length; i++ ) {
			switch( true ) {
				case string.charAt(i) == " ":
					newstring = newstring+'-';
					break;
				case string.charAt(i).match(/[a-z]/) != null:
				case string.charAt(i).match(/[A-Z]/) != null:
				case string.charAt(i).match(/[0-9]/) != null:
					newstring = newstring+string.charAt(i);
					break;
				default:
					newstring = newstring+'_';
					break;
			}
		}
		document.getElementById(destinationID).value=newstring;
	}
}

function stopRewriteURL() {
	allowRewriteURL = false;
}

function checkIfURLIsEmpty(destinationID) {
	if( document.getElementById(destinationID).value != "" ) {
		allowRewriteURL = false;
	}
}


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 ();
}


function smartRedirect( url ) {
	if( url != "" ) {
		setTimeout( "document.location.href='"+url+"';", 3000 );
	}
}


function loadMyTree( countryID ) {
	for( var i=0; i<10; i++) {
		$(".country_"+i).css({ display: "none" });
	}
	$(".country_"+countryID).css({ display: "block" });
}



/* SEARCH JS */



function searchHideTextarea( elemID ) {
	$("#"+elemID).css({ display: "none" });
	$("#"+elemID+"_butt").val("Show input");
}
function searchShowTextarea( elemID ) {
	$("#"+elemID).css({ display: "block" });
	$("#"+elemID+"_butt").val("Hide input");
}
function searchChangeTextarea( elemID ) {
	switch( $("#"+elemID).css("display") ) {
		case "none":
			searchShowTextarea( elemID );
			break;
		case "block":
			searchHideTextarea( elemID );
			break;
	}
}


var actualType;
var actualElemID;

function openSearch( searchType, elemID  ) {
	actualType = searchType;
	actualElemID = elemID;
	var sValues = $("#"+elemID).val();
	opcje = "height=600,width=800,scrollbars=yes,resizable=no,menubar=no";
	w = window.open("/search.html?input="+searchType+"&elements=" + sValues, "", opcje, true);
	w.focus ();
}


function getSearchValues() {
	var values = new Array();
	var counter = 0;
	var checks = $('input[@name="mass_element"]');
	for( var i=0; checks[i]; i++ ) {
		if( checks[i].checked == true ) {
			values[counter] = checks[i].value;
			counter++;
		}
	}
	var result = '';
	$.each( values, function(i, n){
		result = result+n+";";
	});
	document.location='/search.html?input='+opener.actualType+'&elements='+filteredString+'&add='+result;
}


function saveSearchValues() {
	if( opener.$("#"+opener.actualElemID).val(filteredString) ) {
		alert("List was saved successfully!");
		opener.focus();
		window.close();
	}
}
