var isMSIE = false;

//
// GENERAL FUNCTIONS
//

function show(theID) {
	document.getElementById(theID).style.visibility = 'visible';
}

function hide(theID) {
	document.getElementById(theID).style.visibility = 'hidden';
}

function hideAll(divIDs) {
	for (i=0; i<divIDs.length; i++) {
		hide(divIDs[i]);
	}
}

function swapDisplay(theDiv) {
	document.getElementById(theDiv).style.display == "none" ? document.getElementById(theDiv).style.display="" : document.getElementById(theDiv).style.display="none";
}

function swapVisibility(theDiv) {
	document.getElementById(theDiv).style.visibility == 'visible' ? document.getElementById(theDiv).style.visibility='hidden' : document.getElementById(theDiv).style.visibility='visible';
}

function pointerCursor(object) {
	object.style.cursor = 'pointer';
}

function pointerCursorID(theID) {
	document.getElementById(theID).style.cursor = 'pointer';
}

function defaultCursor(object) {
	object.style.cursor = 'default';
}

function defaultCursorID(theID) {
	document.getElementById(theID).style.cursor = 'default';
}

function changeBackground(theID, imageURL) {
	var theBgImg = "url(" + imageURL + ")";
	document.getElementById(theID).style.backgroundImage = theBgImg;
}

function changeBgColor(theID, color) {
	document.getElementById(theID).style.backgroundColor = color;
}

function changeBgColor(object, color) {
	object.style.backgroundColor = color;
}

function noBackground(theID) {
	document.getElementById(theID).style.backgroundImage = 'none';
}

function changeClass(object, theClass) {
	object.className = theClass;
}

function changeClassID(theID, theClass) {
	document.getElementById(theID).className = theClass;
}

function swapClass(theID, classA, classB) {
	if ( document.getElementById(theID).className == classA ) {
		document.getElementById(theID).className = classB;
	} else {
		document.getElementById(theID).className = classA;
	}
}

function reloadParent() {
	window.opener.location.reload();
}

function setDivContent(theDiv, theContent) {
	document.getElementById(theDiv).innerHTML = theContent;
}

function getScreenHeight() {
	if (self.innerHeight) { // All
		return self.innerHeight;
	} else if (document.body) { // IE
		return document.body.clientHeight;
	}
}

function getElementRuntimeHeight(element, theID) {
	if (!element) { element = document.getElementById(theID); }
	return element.offsetHeight;
}

function getElementRuntimeWidth(element, theID) {
	if (!element) { element = document.getElementById(theID); }
	return element.offsetWidth;
}

function handleDarkCover(theCoverID, theParentID) {
	coverElement = document.getElementById(theCoverID);
	parentElement = document.getElementById(theParentID);
	coverElement.style.width = getElementRuntimeWidth(parentElement, '') + "px";
	coverElement.style.height = getElementRuntimeHeight(parentElement, '') + "px";
	swapVisibility(theCoverID);
}

//
// STRING HANDLING FUNCTIONS
//

// Cleans a string
function cleanIt(String) {
	return removeMultipleSpaces(trimIt(replaceLFs(removeMultipleLFs(removeTags(removeTabs(String))))));
}

function adminCleanIt(String) {
	return removeMultipleSpaces(trimIt(replaceLFs(removeMultipleLFs(removeTabs(String)))));
}

// Cleans a string
function justCleanIt(String) {
	return removeMultipleSpaces(trimIt(removeAllLFs(removeTags(removeTabs(String)))));
}

// Trims a string
function trimIt(String) {
	return String.replace(/^\s+|\s+$/g, "");
}

// Removes multiple spaces from a string
function removeMultipleSpaces(String) {
	return String.replace(/\s+/g, " ");
}

// Removes tabs from a string
function removeTabs(String) {
	return String.replace(/\t/g, "");
}

// Removes multiple line feeds (more than two)
function removeMultipleLFs(String) {
	return String.replace(/(\r)*\n((\r)*\n)+/g, "\r\n\r\n");
}

// Removes all the line feeds
function removeAllLFs(String) {
	return String.replace(/(\r)*\n/g, " ");
}

// Removes tags from a string
function removeTags(String) {
	return String.replace(/<.*?>/g, "");
}

// Replaces line feeds with the <br> tag
function replaceLFs(String) {
	return String.replace(/(\r)*\n/g, "<br>");
}

// Replaces the <br> tag with line feeds
function replaceBRs(String) {
	return String.replace(/<br>/g, "\r\n");
}

// Removes backslashes from a string
function removeBackslashes(String) {
	return String.replace(/\\/g, "");
}

//
// FORM VALIDATION FUNCTIONS
//

// Checks if a string is empty
function isEmpty(string) {
	if (string == "" ) {
		return true;
	}
	return false;
}

// Checks if a string has the proper length
function hasGoodLength(string, min, max) {
	var length = string.length;
	if ( length >= min && length <= max ) {
		return true;
	}
	return false;
}

// Validates a URL
function isURLValid(url) {
	var length = url.length;
	if ( length >= 12 && url.substring(0, 4) == "http" ) {
		return true;
	}
	return false;
}

// Validates an e-mail address
function isEmailValid(email) {
	if ( /[a-zA-Z0-9\._\-]+@[a-zA-Z0-9\._\-]+\.[a-zA-Z]{2,4}/.test(email) ) {
		return true;
	}
	return false;
}

// Validates an image type 
function isImageValid(theID) {
	var validImageTypes = ["jpeg", "jpg", "gif", "png", "wbmp", "JPG", "JPEG", "GIF", "PNG", "WBMP"];
	var components = document.getElementById(theID).value.split(".");
	var type = components[components.length-1];
	if ( !existsInArray(type, validImageTypes) ) {
		return false;
	}
	return true;
}

//
// MISCELLANEOUS FUNCTIONS
//

// Counts characters and words
function countCharactersAndWords(String) {
	var cleanString = cleanIt(String);
	var results = [cleanString.length, 0]; // [Characters, Words]
	if (results[0] > 0) {
		results[1] = cleanString.split(" ").length;
	}
	return results;
}

// Sets cell color
function setCellColor(chars, minChars, maxChars, tableName) {
	var tableCell = document.getElementById(tableName).rows[0].cells[0];
	if ( chars < minChars || chars > maxChars ) {
		tableCell.style.backgroundColor = '#333333';
	} else {
		tableCell.style.backgroundColor = '#45B655';
	}
}

// Calculates a percentage
function calculatePercentage(value, total) {
	return value*100/total;
}

// Calculates and sets the width of the cells              
function calculateCellWidths(characters, maxNumberOfCharacters, tableName) {
	var table = document.getElementById(tableName);
	var tableWidth = table.width;
	var usedCellWidth = 0;
	var freeCellWidth = 0;
	if (characters <= maxNumberOfCharacters) {
		var percentage = calculatePercentage(characters, maxNumberOfCharacters);
		usedCellWidth = tableWidth * percentage/100;
		freeCellWidth = tableWidth * (100-percentage)/100;
	} else {
		usedCellWidth = tableWidth;
		freeCellWidth = 0;
	}
	table.rows[0].cells[0].style.width = usedCellWidth;
	table.rows[0].cells[1].style.width = freeCellWidth;
}

// Check if a string exists in an array
function existsInArray(theString, theArray) {
	var found = false;
	for (i=0; i<theArray.length; i++) {
		if ( theString == theArray[i] ) {
			found = true;
			break;
		}
	}
	return found;
}

// Create a multidimensional array
function createMultiDimensionalArray(rows, columns) {
	var i, j;
	var theArray = new Array(rows);
	for (i=0; i<rows; i++) {
		theArray[i] = new Array(columns); 
		for (j=0; j<columns; j++) {
			theArray[i][j] = "";
		}
	}
	return theArray;
}

// Open a window
function openWindow(page, title) {
	window.open (page, title, 'width=620, height=740, toolbar=no, menubar=no, scrollbars=yes, resizable=no, location=no, directories=no, status=no, titlebar=no');
}

// Open a normal window
function openNormalWindow(url) {
	window.open(url);
}

// Reload captcha images
function reloadCAPTCHA() {
	document.getElementById('captchaimg').src = './scripts/securityimage.php?r=' + Math.random();
}

// Add to favorites
function addToFavorites(title, url) {
	if ( window.sidebar ) { // Firefox
		window.sidebar.addPanel(title, url, "");
	} else if ( window.opera && window.print ) { // Opera
		var el = document.createElement('a');
		el.setAttribute('href', url);
		el.setAttribute('title', title);
		el.setAttribute('rel', 'sidebar');
		el.click();
	} else if ( document.all ) { // IE
		window.external.addFavorite(url, title);
	}
}

function facebookShare(url) {
	window.open('http://www.facebook.com/sharer.php?u='+url, '', 'width=650, height=450, toolbar=no, menubar=no, scrollbars=no, resizable=yes, location=yes, directories=no, status=yes, titlebar=no');
}

//
// HTTPREQUEST FUNCTIONS
//

function getContentOnDemand(theURL, theDiv) {

	var xmlhttp = null;

	if ( window.XMLHttpRequest ) {
		xmlhttp = new XMLHttpRequest();
	} else if ( window.ActiveXObject ) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

	try {
		xmlhttp.onreadystatechange = function() {
			if ( xmlhttp.readyState == 4 ) {
				if ( xmlhttp.status == 200 ) {
					document.getElementById(theDiv).innerHTML = xmlhttp.responseText;
					try {
						runOnXMLHttpRequestCompletion(); // Runs (if implemented) on successful completion
					} catch(e) {}
				} else document.getElementById(theDiv).innerHTML = "Αποτυχία αποστολής/λήψης!";
			}
		};
		
		xmlhttp.open("GET", theURL, true);
		xmlhttp.send(null);
		
	} catch(e) {
		alert("Αποτυχία αποστολής/λήψης!");
	}

}

function postContentOnDemand(theData, theURL, theDiv) {

	if ( window.XMLHttpRequest ) {
		xmlhttp = new XMLHttpRequest();
	} else if ( window.ActiveXObject ) {
		xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
	}

	try {
		xmlhttp.onreadystatechange = function() {
			if ( xmlhttp.readyState == 4 ) {
				if ( xmlhttp.status == 200 ) {
					setDivContent(theDiv, xmlhttp.responseText);
					try {
						runOnXMLHttpRequestCompletion(); // Runs (if implemented) on successful completion
					} catch(e) {}
				} else setDivContent(theDiv, "Αποτυχία αποστολής/λήψης!");
			}
		};
		
		xmlhttp.open("POST", theURL, true);
		xmlhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
		xmlhttp.setRequestHeader("Content-length", theData.length);
		xmlhttp.setRequestHeader("Connection", "close");
		xmlhttp.send(theData);
		
	} catch(e) {
		alert("Αποτυχία αποστολής/λήψης!");
	}

}