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

var displayWDA = new Array();

function displayWithDelay(theID) {
	if ( displayWDA[theID] == null || displayWDA[theID][0] == 0 ) {
		alert("in");
		t = setTimeout("displayWithDelayAct('"+theID+"')", 200);
		displayWDA[theID] = [1, t];
	} else displayWithDelayAct(theID);
}

function unDisplayWithDelay(theID) {
	displayWDA[theID][0] = 0;
	clearTimeout(displayWDA[theID][1]);
	document.getElementById(theID).style.display = '';
}

function displayWithDelayAct(theID) {
	if ( displayWDA[theID][0] == 1 ) document.getElementById(theID).style.display = '';
}

function display(theID) {
	document.getElementById(theID).style.display = '';
}

function unDisplay(theID) {
	document.getElementById(theID).style.display = 'none';
}

function displayGDC(theID) {
	display('globalDarkCover');
	display(theID);
}

function unDisplayGDC(theID) {
	unDisplay(theID);
	unDisplay('globalDarkCover');
}

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

function clickLink(theID) {
	var linkElement = document.getElementById(theID);
	var linkHref = trimIt(unescape(linkElement.href));
	if ( linkHref.toLowerCase().substring(0, 11) == "javascript:" ) {
		linkHref = trimIt(linkHref.substring(11));
	}
	eval(linkHref);
}

function isChildOf(parent, child) {
	if( child != null ) {
		while( child.parentNode ) {
			if ( (child = child.parentNode) == parent ) return true;
		}
	}
	return false;
}

// Ignore onMouseOut events when moving to nested elements
function onMouseOutHandler(parent, e, jsCode) {
	var currentMouseTarget = null;
	if (e.toElement) {
		currentMouseTarget = e.toElement;
	} else if (e.relatedTarget) {
		currentMouseTarget = e.relatedTarget;
	}
	if( !isChildOf(parent, currentMouseTarget) && parent != currentMouseTarget ) eval(jsCode);
}

function cancelEvent(e) {
	if (!e) var e = window.event;
	e.cancelBubble = true;
	if (e.stopPropagation) e.stopPropagation();
}

function isEnterKey(e) {
	if (e.keyCode == 13 || e.which == 13) return true;
}

function stopEnterKey(e) {
	if (isEnterKey(e)) cancelEvent(e);
}

// STRING-HANDLING FUNCTIONS

function cleanIt(str) {
	return removeMultipleSpaces(trimIt(replaceLFs(removeMultipleLFs(removeTags(removeTabs(str))))));
}

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

function justCleanIt(str) {
	return removeMultipleSpaces(trimIt(removeAllLFs(removeTags(removeTabs(str)))));
}

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

function removeMultipleSpaces(str) {
	return str.replace(/\s+/g, " ");
}

function removeTabs(str) {
	return str.replace(/\t/g, "");
}

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

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

function removeTags(str) {
	return str.replace(/<.*?>/g, "");
}

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

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

function removeBackslashes(str) {
	return str.replace(/\\/g, "");
}

// FORM-VALIDATION FUNCTIONS

function isEmpty(str) {
	if (str == "" ) return true;
	return false;
}

function hasGoodLength(string, min, max) {
	var length = string.length;
	if ( length >= min && length <= max ) {
		return true;
	}
	return false;
}

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

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

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

// MISC FUNCTIONS

function randomInRange(from, to) {
	return Math.floor(Math.random()*(to-from+1)+from);
}

function pixelsToInt(pxStr) {
	return pxStr.match(/\d+/) * 1;
}

function countCharactersAndWords(str) {
	var cleanStr = cleanIt(str);
	var results = [0, 0];
	if (cleanStr) {
		results[0] = cleanStr.length;
		results[1] = cleanStr.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 = '#EE0000';
	} else tableCell.style.backgroundColor = '#00CC00';
}

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

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

function existsInArray(theString, theArray) {
	var found = false;
	for (i=0; i<theArray.length; i++) {
		if ( theString == theArray[i] ) {
			found = true;
			break;
		}
	}
	return found;
}

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

function createOptionsCSV(element) {
	var object = document.getElementById(element);
	var csvStr = "";
	for (i=0; i<object.length; i++) {
		if (object.options[i].selected == true ) csvStr += object.options[i].value + ",";
	}
	return csvStr.substring(0, csvStr.length-1); 
}

function openWindow(page, title) {
	window.open (page, title, 'width=610, height=700, toolbar=no, menubar=no, scrollbars=yes, resizable=no, location=no, directories=no, status=no, titlebar=no');
}
function openWindowSz(page, title, width, height) {
	window.open (page, title, 'width=' + width + ', height=' + height + ', toolbar=no, menubar=no, scrollbars=yes, resizable=no, location=no, directories=no, status=no, titlebar=no');
}

function openNormalWindow(url) {
	window.open(url);
}

function reloadCAPTCHA() {
	document.getElementById('captchaimg').src = 'http://www.enfo.gr/scripts/securityimage.php?r=' + Math.random();
}

function likeObjectDisable(id, likes) {
	var lkImgObjs = document.getElementsByName(id+'lkImg');
	var lkTxtObjs = document.getElementsByName(id+'lkTxt');
	var likesPlus = likes*1 + 1;
	for (i=0; i<lkImgObjs.length; i++) {
		lkImgObjs[i].title='μόλις ψήφισες';
		lkImgObjs[i].disabled=true;
		lkTxtObjs[i].innerHTML=likesPlus;
	}
}

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, theFunction, theFunctionArgs) {

	var xmlhttp = null;
	var returnHTML = null;
	var xmlhttpSuccess = 0;

	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 ) {
					returnHTML = xmlhttp.responseText;
					xmlhttpSuccess++;
				} else returnHTML = "Αποτυχία αποστολής/λήψης!";
				if ( theDiv ) document.getElementById(theDiv).innerHTML = returnHTML;
				try {
					if ( theFunction && xmlhttpSuccess > 0 ) {
						if ( theFunctionArgs ) {
					 		theFunction(theFunctionArgs);
					 	} else theFunction();
					}
				} catch(e) {}
			}
		};
		xmlhttp.open("GET", theURL, true);
		xmlhttp.send(null);
	} catch(e) {
		alert("Αποτυχία αποστολής/λήψης!");
	}

}

function postContentOnDemand(theData, theURL, theDiv, theFunction, theFunctionArgs) {

	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 {
						if ( theFunction ) { // Runs on successful completion
							if ( theFunctionArgs ) {
						 		theFunction(theFunctionArgs);
						 	} else theFunction();
						 }
					} 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("Αποτυχία αποστολής/λήψης!");
	}

}
