/**
* Common javascript functions
* @author Tsvetomir Velichkov
* @version 2.0
**/

var dimmerDensity = 65; //in %
var popupTimeout = 3000; //in ms

//Global variables. DONT EDIT BELOW!!!
var popupLocked	 		= false;		//Sets the popup state to locked so it will stay on the screen
var popupVisible		= false;		//Checks if the popup is visible
var errorMessage 		= null;			//If some error occured
var hideMessageOnLoad 	= false;		//If must hide message on load
var	debugMode	 		= false;		//Enables debug mode
var instantMessage 		= null;			//
var pageLoaded 	 		= false;		//Checks if the page is loaded
var GET_DATA	 		= new Array();
var preloaderArr 		= new Array();
var showQueue	 		= new Array();
//Current window dimensions
var windowHeight;
var windowWidth;
//Current scroll
var windowScrollX;
var windowScrollY;
//Popoup size
var popupWidth;
var popupHeight;
//Mouser position relative to the body
var posx = 0;
var posy = 0;
//Position relative to the current screen
var posx1 = 0;
var posy1 = 0;
var mouseTarget = '';
var h = '';
var charscount=0;
var forcedShow = false;

var isIE = document.all ? 1 : 0;
var isIE6 = /msie|MSIE 6/.test(navigator.userAgent);

/** Check for default **/
if (typeof WEBPATH == 'undefined' || WEBPATH == '') alert("Warning you must set the WEBPATH var");
if (typeof Prototype == 'undefined') alert("Prototype is required but is missing");

//Basic initialization
window.onload = function() {
	pageLoaded = true;

	//systemInit();

	//If must hide some popup on page load
	if (hideMessageOnLoad) setTimeout('popupLocked=false; hidePopup();', popupTimeout);

	//Check for common loader
	if (typeof loadGeoMap == 'function') loadGeoMap();
	if (typeof loader == 'function') loader();
	//Call init functions
	if (typeof initInfoBar == 'function') 	initInfoBar();
	if (typeof uploadStatus == 'function') 	uploadStatus();
	if (typeof loadPhoto == 'function') 	loadPhoto();
	if (typeof initHS == 'function') 		h = new initHS();
	if (typeof resizePhotoTd == 'function') resizePhotoTd();
	if (typeof publishStream == 'function') publishStream();

	//Add submit button to forms
	fixForms();
}

function getElementsByTagNames(list,obj) {
	if (!obj) var obj = document;

	var tagNames = list.split(',');
	var resultArray = new Array();
	for (var i=0;i<tagNames.length;i++) {
		var tags = obj.getElementsByTagName(tagNames[i]);
		for (var j=0;j<tags.length;j++) {
			resultArray.push(tags[j]);
		}
	}
	var testNode = resultArray[0];
	if (!testNode) return [];
	if (testNode.sourceIndex) {
		resultArray.sort(function (a,b) {
				return a.sourceIndex - b.sourceIndex;
		});
	}
	else if (testNode.compareDocumentPosition) {
		resultArray.sort(function (a,b) {
				return 3 - (a.compareDocumentPosition(b) & 6);
		});
	}
	return resultArray;
}

function fixForms(elem) {
	var forms = null;
	if (typeof elem != 'undefined') forms = getElementsByTagNames("FORM", elem);
	else forms = getElementsByTagNames("FORM");

	for (i=0;i<forms.length;i++) {
		var haveSubmit = false;
		appendToLog('Form '+(typeof forms[i].id != 'undefined' ? forms[i].id : ('#'+i))+' has '+forms[i].elements.length+' elements.');

		for (j=0;j<forms[i].elements.length;j++) {
			if (forms[i].elements[j].type == 'submit') haveSubmit = true;
		}

		appendToLog('Form '+(typeof forms[i].id != 'undefined' ? forms[i].id : ('#'+i))+' has submit: '+haveSubmit);

		if (!haveSubmit) {
			var submit = document.createElement('INPUT');
			submit.type = 'SUBMIT';
			submit.name = 'submit_button'+i;
			submit.value = '';
			submit.style.position="absolute";
			submit.style.width="0";
			submit.style.height="0";
			submit.className="noStyle";
			//submit.style.visibility="hidden";

			forms[i].appendChild(submit);
		}
	}
}

function systemInit() {
	rs(); 			//Get the initial sizes
	initDimmer(); 	//Prepare the dimmer
	initPopup();
	initIFrame();
	initialiseGetData();

	callOnLoad();

	if (errorMessage) {
		populatePopup(errorMessage);
		showCenteredPopup();
		popupLocked = true;
		hideMessageOnLoad = true;
		//setTimeout('popupLocked=false; hidePopup();', popupTimeout);
	}

	if (instantMessage) {
		populatePopup(instantMessage);
		showDimmer(true);
		showCenteredPopup();
		popupLocked = true;
	}
}

function callOnLoad() {
	rs();
	window.setInterval("rs()", 2000);


	document.onmousemove = function(e) {

		var targ;
		if (!e) e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3)	targ = targ.parentNode;
		mouseTarget = targ;

		if (e.pageX || e.pageY) 	{
			posx = e.pageX;
			posy = e.pageY;
			posx1 = e.pageX - windowScrollX;
			posy1 = e.pageY - windowScrollY;
		}
		else if (e.clientX || e.clientY) 	{
			posx = e.clientX + document.body.scrollLeft + document.documentElement.scrollLeft;
			posy = e.clientY + document.body.scrollTop + document.documentElement.scrollTop;
			posx1 = e.clientX;
			posy1 = e.clientY;
		}
		// posx and posy contain the mouse position relative to the document

		if (!pageLoaded && !forcedShow) return true;

		if ($('dg') != null && debugMode==true) {
			$('dg').innerHTML = '<table><tr>'+'<td><strong>body W:</strong></td><td>'+document.body.clientWidth+'px;</td><td><strong>Scroll X:</strong></td><td>'+windowScrollX+'</td><td><strong>Window W:</strong></td><td>'+windowWidth+'</td><td><strong>mouse X:</strong></td><td>'+posx+'</td><td><strong>screen X:</strong></td><td>'+posx1+'</td><td><strong>popup locked:</strong></td><td>'+popupLocked +';</td><td><strong>popup left:</strong></td><td>'+$('popup').style.left+'</td><td><strong>popup W:</strong></td><td>'+popupWidth+'px</td></tr>'+
			'<td><strong>body H:</strong></td><td>'+document.body.clientHeight+'px; </td><td><strong>Scroll Y:</strong></td><td>'+windowScrollY+'</td><td><strong>Window H:</strong></td><td>'+windowHeight+'</td><td><strong>mouse Y:</strong></td><td>'+posy+'</td><td><strong>screen Y:</strong></td><td>'+posy1+'</td><td> <strong>popup visible:</strong></td><td>'+popupVisible+';</td><td><strong>popup top:</strong></td><td>'+$('popup').style.top+'</td><td><strong>popup H:</strong></td><td>'+popupHeight+"px</td></tr></table>";
		}

		if ((typeof modelProfileVisible != 'undefined' && modelProfileVisible==true) || (typeof otherProfileVisible != 'undefined' &&  otherProfileVisible==true)) {
			//Show the popup at right position
			setOnScreen();
		}

		//Picture Gallery: Picture controls
		if (typeof visible_picture_id != 'undefined' && visible_picture_id != null) {
			var in_menu = lookInParent(targ);
			//$('dg').innerHTML += visible_picture_id + " " + in_menu +"<br />";
			if (!in_menu) {
				deactivatePic(visible_picture_id);
			}
		}
	}

	window.onscroll = function(e) {
		if (!pageLoaded && !forcedShow) return false;
		rs();

		if ((typeof modelProfileVisible != 'undefined' && modelProfileVisible==true) || (typeof otherProfileVisible != 'undefined' &&  otherProfileVisible==true)) {
			hidePopup();
		}

		if ($('dg') != null) {
			$('dg').style.left = '0px';
			$('dg').style.top = windowScrollY+'px';
		}

		if ($('helper')) {
			$('helper').style.left = '50px';
			$('helper').style.top = windowScrollY+'px';
		}
	}

	document.onkeydown = function (e) {
		if (!pageLoaded && !forcedShow) return true;

		var targ;
		if (!e) e = window.event;
		if (e.target) targ = e.target;
		else if (e.srcElement) targ = e.srcElement;
		if (targ.nodeType == 3)	targ = targ.parentNode;

		if (e.ctrlKey && e.altKey && e.keyCode==68) hideDimmer(true);


		if ($('galleryPicture') != null && targ.tagName != 'TEXTAREA' && targ.tagName != 'INPUT' && targ.tagName != 'SELECT') {
			if (e.keyCode == 39) {
				getNext();
			}else if (e.keyCode == 37) {
				getPrev();
			}
		}
	}
}


/**
*	Dimmer
*/

function initDimmer() {
	var dim = document.createElement('div');
	dim.id					= 'dimmer';
	dim.style.position 		= 'absolute';
	dim.style.background 	= 'black';
	dim.style.display 		= 'none';
	dim.style.zIndex		= 100;
	//Set the opacity valie
	dim.style.opacity		= dimmerDensity/100;
	dim.style.filter		= 'alpha(opacity='+dimmerDensity+')';
	//Onclick we set the close handler and popup
	//dim.onclick = function (e) { hideDimmer(true); }

	document.body.appendChild(dim);
}

function showDimmer(disableCloseEvent) {
	if (!pageLoaded && !forcedShow) return false;
	rs();

	if (typeof disableCloseEvent != 'undefined' && disableCloseEvent==true) {
		$('dimmer').onclick = function (e) {  }
	}else{
		//Onclick we set the close handler and popup
		$('dimmer').onclick = function (e) { hideDimmer(true); }
	}

	$('dimmer').style.left = '0px';
	$('dimmer').style.top = '0px';
	$('dimmer').style.width = document.body.clientWidth + 'px';
	$('dimmer').style.height = document.body.clientHeight + 'px';
	$('dimmer').style.display = 'block';

	//Showing the dimmer we must init the iframe or we see sucking SELECTs
	positionIFrame(0,0);
	showIFrame(document.body.clientWidth, document.body.clientHeight);
}

function hideDimmer(bhidePopup) {
	if (!pageLoaded && !forcedShow) return false;
	if (popupLocked) return false;

	$('dimmer').style.display = 'none';
	//If we need to close the popup too
	if (typeof bhidePopup != 'undefined' && bhidePopup == true) hidePopup();

	//Hide the iframe because it is not needed anymore
	hideIFrame();
}

/**
*	IFrame
*/


/**
*	Function to initialize the IFrame
**/
function initIFrame() {
	if (!document.all) return true;

	var iframe = document.createElement('iframe');
	iframe.id					= 'iframe';
	iframe.style.zIndex 		= 99;
	iframe.style.position 		= 'absolute';
	iframe.style.display		= 'none';
	iframe.frameBorder 			= 0;
	//iframe.style.border			= '1px solid red';
	iframe.style.left			= 0;
	iframe.style.top 			= 0;
	iframe.style.background		= 'transparent';
	iframe.style.filter			= 'alpha(opacity=0)'; //Set the alpha transparency to make the iframe transparent in IE. "allowtransparent" wont work

	document.body.appendChild(iframe);
}

/**
* 	Position the IFrame at some point in the XY
*
*	@param int l - left offset
*	@param int t - top offset
**/
function positionIFrame(l, t) {
	if (!document.all) return true;
	if (!pageLoaded && !forcedShow) return false;

	$('iframe').style.left 	= l + 'px';
	$('iframe').style.top 	= t + 'px';
}

/**
* 	Shows the IFrame with some width and height
*
*	@param int w - width
*	@param int h - height
**/
function showIFrame(w, h) {
	if (!document.all) return true;
	if (!pageLoaded && !forcedShow) return false;

	$('iframe').style.width 	= w + 'px';
	$('iframe').style.height 	= h + 'px';
	if (!window.opera) $('iframe').style.display 	= 'block';
}

/**
* 	Sets the IFrame invisible
**/
function hideIFrame() {
	if (!document.all) return true;
	if (!pageLoaded && !forcedShow) return false;

	$('iframe').style.display = 'none';
}

/**
*	Popup
*/

/**
*	Function to initialize the Popup table
**/
function initPopup() {
	var popup = document.createElement('table');

	//Some basic attributes are set
	popup.id 					= 'popup';
	popup.style.position 		= 'absolute';
	popup.style.left 			= 0;
	popup.style.top				= 0;
	popup.style.borderCollapse 	= 'collapse';
	popup.style.visibility 		= 'hidden';
	popup.style.zIndex 			= 101;

	var tbody = document.createElement('tbody');

	//We create grid 3x3
	//Create the first row...
	var tr = document.createElement('tr');

	var td1 = document.createElement('td');
	td1.style.padding 				= '0';
	td1.style.backgroundImage		= 'url('+CDN_PATH+'images/frame/frame_corners.png)';
	td1.style.backgroundPosition 	= '0 0';
	if (isIE6) td1.style.behavior	= 'url('+WEBPATH+'js/iepngfix.htc)';
	td1.width 						= '20';
	td1.height 						= '20';

	var td2 = document.createElement('td');
	td2.style.padding 				= '0';
	td2.style.background 			= 'url('+CDN_PATH+'images/frame/frame_bgnd_top.png)';
	if (isIE6) td2.style.behavior	= 'url('+WEBPATH+'js/iepngfix.htc)';
	td2.height 						= '20';
	td2.innerHTML 					= '&nbsp;';

	var td3 = document.createElement('td');
	td3.style.padding 				= '0';
	td3.style.backgroundImage		= 'url('+CDN_PATH+'images/frame/frame_corners.png)';
	td3.style.backgroundPosition 	= '-20px 0';
	if (isIE6) td3.style.behavior	= 'url('+WEBPATH+'js/iepngfix.htc)';
	td3.width 						= '20';
	td3.height 						= '20';
	//td3.innerHTML 				= '&nbsp;';

	tr.appendChild(td1);
	tr.appendChild(td2);
	tr.appendChild(td3);

	tbody.appendChild(tr);

	//Create the second row...
	var tr = document.createElement('tr');

	var td1 = document.createElement('td');
	td1.style.padding 				= '0';
	td1.style.background 			= 'url('+CDN_PATH+'images/frame/frame_bgnd_left.png)';
	if (isIE6) td1.style.behavior	= 'url('+WEBPATH+'js/iepngfix.htc)';


	var td2 = document.createElement('td');
	td2.id							= 'tblContentTd';
	td2.style.width					= 'auto';
	td2.style.height				= 0;
	td2.style.padding 				= '0';
	td2.style.background 			= 'black';
	td2.style.position	 			= 'relative';
	td2.style.background 			= 'url('+CDN_PATH+'images/frame/frame_bgnd.png)';
	if (isIE6) td2.style.behavior	= 'url('+WEBPATH+'js/iepngfix.htc)';
	td2.innerHTML 					= '<div class="relative" id="tblContent"><img src="'+WEBPATH+'images/preloader.gif" /></div>';
	td2.style.color					= "white";

	var td3 = document.createElement('td');
	td3.style.padding 				= '0';
	td3.style.background 			= 'url('+CDN_PATH+'images/frame/frame_bgnd_right.png)';
	if (isIE6) td3.style.behavior	= 'url('+WEBPATH+'js/iepngfix.htc)';
	td3.innerHTML 					= '&nbsp;';

	tr.appendChild(td1);
	tr.appendChild(td2);
	tr.appendChild(td3);

	tbody.appendChild(tr);

	//Create the last row...
	var tr = document.createElement('tr');

	var td1 = document.createElement('td');
	td1.style.padding 				= '0';
	td1.style.backgroundImage		= 'url('+CDN_PATH+'images/frame/frame_corners.png)';
	td1.style.backgroundPosition 	= '0 -20px';
	if (isIE6) td1.style.behavior	= 'url('+WEBPATH+'js/iepngfix.htc)';

	var td2 = document.createElement('td');
	td2.style.padding 				= '0';
	td2.style.background 			= 'url('+CDN_PATH+'images/frame/frame_bgnd_bottom.png)';
	if (isIE6) td2.style.behavior	= 'url('+WEBPATH+'js/iepngfix.htc)';
	td2.height 						= '20';
	td2.innerHTML 					= '&nbsp;';

	var td3 = document.createElement('td');
	td3.style.padding 				= '0';
	td3.style.backgroundImage		= 'url('+CDN_PATH+'images/frame/frame_corners.png)';
	td3.style.backgroundPosition 	= '-20px -20px';
	if (isIE6) td3.style.behavior	= 'url('+WEBPATH+'js/iepngfix.htc)';
	td3.innerHTML 					= '&nbsp;';

	tr.appendChild(td1);
	tr.appendChild(td2);
	tr.appendChild(td3);

	tbody.appendChild(tr);

	//We need the TBODY to create table in Internet Explorer :-(
	popup.appendChild(tbody);

	document.body.appendChild(popup);
}

/**
*	Moves the popup at some point
*
*	@param int l 	- left
*	@param int t	- top
**/
function movePopup(l, t) {
	if ((!pageLoaded && !forcedShow) || popupLocked) return false;

	if (t < 0) t = 0;

	$('popup').style.left 	= l + 'px';
	$('popup').style.top 	= t + 'px';

	if ($('iframe') && $('iframe').style.display=='block') {
		positionIFrame(l, t);
	}
}

function fillPopup(data, show) {
	populatePopup(data, show);
}

/**
*	This function is generally used to change the popup content and to show it if necessery
*
*	@param string data 	- The innerHTML
*	@param bool show	- If true we set popup visible
**/
function populatePopup(data, show) {
	if ((!pageLoaded && !forcedShow) || popupLocked) return false;

	$('tblContent').innerHTML = data;
	popupWidth 	= parseInt($('tblContentTd').clientWidth);
	popupHeight	= parseInt($('tblContentTd').clientHeight);

	//If show is true we set the popup visible
	if (typeof show != 'undefined' && show==true) showPopup();
}

/**
*	Resize the popup to fit the content
**/
function resizePopup() {
	if ((!pageLoaded && !forcedShow) || popupLocked) return false;

	$('tblContent').style.width 	= popupWidth + 'px';
	$('tblContent').style.height 	= popupHeight + 'px';
}

/**
*	Sets the popup visible
**/
function showPopup() {
	if ((!pageLoaded && !forcedShow) || popupLocked) return false;

	$('popup').style.visibility = 'visible';
	popupVisible = true;

	//If the iframe is not visible we must set it visible
	if ($('iframe') && $('iframe').style.display!='block') {
		positionIFrame(parseInt($('popup').style.left), parseInt($('popup').style.top));
		showIFrame($('popup').clientWidth, $('popup').clientHeight);
	}

	//Add submit button to forms
	fixForms($('tblContent'));
}

/**
*	Move the popup to be centered against the new content size/position
**/
function reCenterPopup() {
	popupWidth 	= parseInt($('tblContentTd').clientWidth);
	popupHeight	= parseInt($('tblContentTd').clientHeight);

	movePopup(windowScrollX+(windowWidth/2 - popupWidth/2), windowScrollY+(windowHeight/2 - popupHeight/2));
}

function setOnScreen() {
	var moveX=0;
	var moveY=0;
	//Show the popup at right position
	if (posy1+popupHeight+60 > windowHeight) { //Position over/under the mouse
		moveY = posy-popupHeight-50;
	}else{
		moveY = posy+20;
	}
	if (windowWidth < (posx1+popupWidth+60)) {
		moveX = posx-popupWidth-40;
	}else{
		moveX = posx+20;
	}

	if (moveX < 0) moveX = 0;
	if (moveY < 0) moveY = 0;

	movePopup(moveX, moveY);
}

/**
*	Same as showPopup() but centers it on the screen
**/
function showCenteredPopup(bShowDimmer) {
	if ((!pageLoaded && !forcedShow) || popupLocked) return false;

	rs(); //Get current offset
	movePopup(windowScrollX+(windowWidth/2 - popupWidth/2), windowScrollY+(windowHeight/2 - popupHeight/2));
	showPopup(); //Show the popup

	if (typeof bShowDimmer != 'undefined' && bShowDimmer==true) {
		showDimmer();
	}
}

/**
*	Function to hide the popup
**/
function hidePopup() {

	if ((!pageLoaded && !forcedShow) || popupLocked) return;
	popupVisible = false;

	//Set the inner part to preloader
	$('tblContent').innerHTML = ''; //<img src="'+WEBPATH+'images/preloader.gif" />
	$('popup').style.visibility = 'hidden';
	hideIFrame();
}

/**
* Call this funkction whenever you need to update the screen size/offset
**/

function rs() {

	if (!document.all) { //All browsers except IE
		windowWidth 	= window.innerWidth-20;
		windowHeight 	= window.innerHeight;
		windowScrollX 	= window.pageXOffset;
		windowScrollY 	= window.pageYOffset;
	}else if (document.documentElement && ( document.documentElement.clientWidth || document.documentElement.clientHeight ) ) { //IE in DTD
		windowWidth 	= document.documentElement.clientWidth-20;
		windowHeight 	= document.documentElement.clientHeight;
		windowScrollX 	= document.documentElement.scrollLeft;
		windowScrollY 	= document.documentElement.scrollTop;
	}else{ //Normal IE
		windowWidth 	= document.body.clientWidth-20;
		windowHeight 	= document.body.clientHeight;
		windowScrollX 	= document.body.scrollLeft;
		windowScrollY 	= document.body.scrollTop;
	}
}

/**
*
**/
function addToQueue(text, bShowDimmer) {
	showQueue[showQueue.length] = new Array(text, bShowDimmer);
}

function showQueueEntries() {
	if (showQueue.length == 0) return;
	hidePops();

	fillPopup('<img src="/images/frame/frame_tfp_close.png" alt="close" style="position:absolute; right: -5px; top: -0px;cursor: pointer" onclick="getNextInQueue()" />'+showQueue[0][0]);
	showCenteredPopup(showQueue[0][1]);

	showQueue.shift();
}

function getNextInQueue() {
	hidePops();
	hideDimmer();
	showQueueEntries();
}

/**
*	Function to check a group of checkboxes
*
*	@param string formElement - Target form name
*	@param boolean checkState - True/false for checked state
**/
function checkAll(formElement, checkState) {
	if (typeof document.forms[formElement] != 'undefined') {
		var myForm = document.forms[formElement];
		for (i=0; i < myForm.elements.length; i++) {
			if (myForm.elements[i].type == 'checkbox') {
				myForm.elements[i].checked = checkState;
			}
		}
	}else{
		alert("Invalid form element provided!");
	}
}

function emoticon(text,txtarea) {

	text = ' ' + text + ' ';

	if (txtarea.createTextRange && txtarea.caretPos) {

		var caretPos = txtarea.caretPos;
		caretPos.text = caretPos.text.charAt(caretPos.text.length - 1) == ' ' ? caretPos.text + text + ' ' : caretPos.text + text;
		txtarea.focus();
	} else {
		txtarea.value  += text;
		txtarea.focus();
	}
}
function insertEmotionMce(text) {

	text = '&nbsp;' + text + '&nbsp;';
	tinyMCE.execCommand('mceInsertContent', false, '');// focus hack;
	tinyMCE.execCommand('mceInsertContent', false, text);

}

function initialiseGetData(){

	var getDataString=new String(window.location);
	var questionMarkLocation=getDataString.search(/\?/);
	if (questionMarkLocation!=-1){
		getDataString=getDataString.substr(questionMarkLocation+1);
		var getDataArray=getDataString.split(/&/g);
		for (var i=0;i<getDataArray.length;i++){
			var nameValuePair=getDataArray[i].split(/=/);
			GET_DATA[unescape(nameValuePair[0])]=unescape(nameValuePair[1]);
		}
	}
}

function $_GET(param) {
	if (typeof GET_DATA[param] != 'undefined') {
		return GET_DATA[param];
	}

	return '';
}

function showHideCommentForm(show) {
	var field = document.getElementById('newCommentLayer');
	if(field.style.display == "none") {
		field.style.display = "block";
		//document.images['menu_marker'].src = IMGPATH+"comments_pointer_down.gif";
	} else {
		if(show == 1) return;
		field.style.display = "none";
		//document.images['menu_marker'].src = IMGPATH+"comments_pointer.gif";
	}
}

function countMsgCharacters(obj,chars) {
	msg= obj.value;
	len = msg.length;
	if (len >chars){
		obj.value=msg.substr(0,charscount);
	}else{
		charscount=len;
	}

	document.getElementById('remainingChars').value=chars-charscount;
}

function changeBorder(id)
{
	if($('cbapp_'+id).checked) {
		if($('cb18_'+id).checked) $('pic'+id).style.border = '3px solid #DC1786';
		else $('pic'+id).style.border = '3px solid #009900';
	} else {
		$('pic'+id).style.border = '3px solid #FF0000';
	}
}



function checkStates(elem) {
	if (elem.value == 1) {
		$('state').disabled=false;
	}else{
		$('state').disabled=true;
	}
}

function findParent(elem, targetClass) {
	var state = false;
	if ((elem.parentNode != null) && elem.parentNode.className != targetClass) {
		state = findParent(elem.parentNode, targetClass);
	}else if ((elem.parentNode != null) && elem.parentNode.className == targetClass) {
		state = true;
	}

	return state;
}

preloader('upload', '/images/uploadbar.gif');
preloader('progress', '/images/preloader.gif');

function preloader(position, images) {
	preloaderArr[position] = new Image();
	preloaderArr[position].src = images;
}

function getImage(position) {
	if (typeof preloaderArr[position] != 'undefined') {
		return preloaderArr[position].src;
	}
}

function showHideCasting(plus, cast_id) {
	if(document.getElementById(cast_id).style.display == 'none') {
		plus.innerHTML = '<img src="/images/str_on.gif">';
		document.getElementById(cast_id).style.display = "block";
	} else {
		plus.innerHTML = '<img src="/images/str.gif">';
		document.getElementById(cast_id).style.display = "none";
	}
}

//JS logger
function appendToLog(data) {
	//return false;
	if (!debugMode) return false;

	var currentTime = new Date();
	var hours = currentTime.getHours();
	var minutes = currentTime.getMinutes();
	var seconds = currentTime.getSeconds();

	$('dg2').innerHTML += hours+':'+minutes+":"+seconds+' - ' + data + "<br />";

	$('dg2').style.visibility = 'visible';
	$('dg2').style.height 	  = '150px';
}

function get_curl() {
	var string = '';

	var getDataString=new String(window.location);
	var questionMarkLocation=getDataString.search(/\?/);
	if (questionMarkLocation!=-1){
		getDataString=getDataString.substr(questionMarkLocation+1);
		var getDataArray=getDataString.split(/&/g);
		for (var i=0;i<getDataArray.length;i++){
			var nameValuePair=getDataArray[i].split(/=/);
			string += unescape(nameValuePair[0])+"="+encodeURIComponent(unescape(nameValuePair[1]))+"&";
		}
	}

	string = string.substr(0, string.length-1);

	return string;
}

function show_error(msg) {
	return '<div class="flashmsg error"><img src="/images/ico_error.png" alt="" align="absmiddle" class="msgIco" />&nbsp;'+languages['must_be_logged_txt']+'</div>';
}

function submitParentForm(elem, elemname, value) {
	saveButtonClicked = true;
	if (typeof elem.parentNode != 'undefined') {
		if (elem.parentNode.tagName == 'FORM') {
			if (typeof elemname != 'undefined') { //we need to create an element and append it
				var input 	= document.createElement('INPUT');
				input.type 	= 'hidden';
				input.name 	= elemname;
				input.value = (typeof value != 'undefined') ? value : elemname;

				elem.parentNode.appendChild(input);
				//appendToLog("");
			}

			appendToLog((typeof elem.parentNode.id != 'undefined' ? 'Submitting '+elem.parentNode.id : null));
			if (elem.parentNode.submit()) {

//			}else{
//				appendToLog("Error. Trying another way");
//				for (var i=0; i< elem.parentNode.elements.length; i++) {
//					if (elem.parentNode.elements[i].type == 'submit') {
//						appendToLog("Found submit element. Clicking it.");
//						elem.parentNode.elements[i].click();
//					}
//				}

			}
//			return false;
//			return true;
		}else{
			submitParentForm(elem.parentNode, elemname, value);
		}
	}
}

function setButtonValue(field) {
	document.getElementById(field).value = '1';
	return true;
}

function confirmAndSet(field, conf_str) {
	if(confirm(conf_str)) {
		document.getElementById(field).value = '1';
		return true;
	}else
		return false;
}

function microtime(get_as_float) {
    // http://kevin.vanzonneveld.net
    // +   original by: Paulo Ricardo F. Santos
    // *     example 1: timeStamp = microtime(true);
    // *     results 1: timeStamp > 1000000000 && timeStamp < 2000000000

    var now = new Date().getTime() / 1000;
    var s = parseInt(now, 10);

    return (get_as_float) ? now : (Math.round((now - s) * 1000) / 1000) + ' ' + s;
}

function infoWindow(text, args) {
	this.element = $(args['elem']);

	var posY = findPosY(this.element);
	var posX = findPosX(this.element);

	this.content = document.createElement('DIV');
	this.content.innerHTML = 'test';
	this.content.style.position	= 'absolute';
	this.content.style.top		= posY + 'px';
	this.content.style.left		= (this.element.offsetWidth + posX + 10) + 'px';
	this.content.style.border	= '1px solid red';

	document.body.appendChild(this.content);
}

function toggleWorksafe(state) {
	new Ajax.Request('/pages/worksafe/'+state, {method: "GET", onSuccess: refreshWindow});
}

var refreshWindow = function (t) {
	window.location.reload();
}