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

/** 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");

var dimmerDensity = 80; //in %

//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 jsInfoBox = null;
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();
//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 = '';

//Basic initialization
window.onload = function() {
	rs(); 			//Get the initial sizes
	initDimmer(); 	//Prepare the dimmer
	initPopup();
	initIFrame();
	initialiseGetData();
	pageLoaded = true;

	//Check for common loader
	if (typeof loader == 'function') {
		loader();
	}

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

	if (jsInfoBox) {
		populatePopup(jsInfoBox);
		showCenteredPopup();
		popupLocked = true;

	}

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

	}

	if (typeof initInfoBar == 'function') {
		initInfoBar();
	}

	if (typeof initHS == 'function') {
		h = new initHS();
		//helper.show(0);
	}

}

document.onmousemove = function(e) {
	if (!pageLoaded) return false;
	rs();

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

	//The info bar from the popup
	if (typeof myAnim != 'undefined' && typeof myAnim.attributes != 'undefined') {
//		var parent = findParent(mouseTarget, 'galleryImage');
//		if (!parent) {
//			myAnim.attributes.width = { to: 0 };
//			myAnim.animate();
//			delete myAnim;
//		}
	}
}

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

//	if ($('dimmer').style.display == 'block') {
//		showDimmer()
//	}

	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) return false;

	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) 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) 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() {
	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 (!pageLoaded) 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 (!pageLoaded) return false;
	if (!document.all) return false;

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

/**
 * 	Sets the IFrame invisible
 **/
function hideIFrame() {
	if (!pageLoaded) 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.className 			= '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.className 			= 'top-left';
	td1.innerHTML 			= '<img src="'+WEBPATH+'images/popup/popup_top_left.png" />';

	var td2 = document.createElement('td');
	td2.className 			= 'top';
	td2.innerHTML 			= '<img src="'+WEBPATH+'images/popup/15x15.png" />';

	var td3 = document.createElement('td');
	td3.className 			= 'top-right';
	td3.innerHTML 			= '<img src="'+WEBPATH+'images/popup/popup_top_right.png" />';

	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.className 			= 'left';
	td1.innerHTML 			= '<img src="'+WEBPATH+'images/popup/15x15.png" />';
	*/
	
	var td2 = document.createElement('td');
	td2.id					= 'tblContent';
	td2.className			= 'content';
	td2.innerHTML 			= '<img src="'+WEBPATH+'images/preloader.gif" />';
	td2.style.color			= "black";

	/*
	var td3 = document.createElement('td');
	td3.className 			= 'right';
	td3.innerHTML 			= '<img src="'+WEBPATH+'images/popup/15x15.png" />';
	*/
	
	//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.className 			= 'bottom-left';
	td1.innerHTML 			= '<img src="'+WEBPATH+'images/popup/popup_bottom_left.png" />';

	var td2 = document.createElement('td');
	td2.className 			= 'bottom';
	td2.innerHTML 			= '<img src="'+WEBPATH+'images/popup/15x15.png" />';

	var td3 = document.createElement('td');
	td3.className 			= 'bottom-right';
	td3.innerHTML 			= '<img src="'+WEBPATH+'images/popup/popup_bottom_right.png" />';

	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 string data 	- The innerHTML
 *	@param bool show	- If true we set popup visible
 **/
function movePopup(l, t) {
	if (!pageLoaded || popupLocked) return false;

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

	if ($('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 || popupLocked) return false;

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

	//Resizes the popup to fit content
	//resizePopup();

	//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 || popupLocked) return false;

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

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

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

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

/**
 *	Move the popup to be centered against the new content size/position
 **/
function reCenterPopup() {
	popupWidth 	= parseInt($('tblContent').clientWidth);
	popupHeight	= parseInt($('tblContent').clientHeight);
	$('popup').style.left 	= windowScrollX+(windowWidth/2 - popupWidth/2) + 'px';
	$('popup').style.top 	= windowScrollY+(windowHeight/2 - popupHeight/2) + 'px';
}

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;
		}
		movePopup(moveX, moveY);
}

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

	rs(); //Get current offset
	$('popup').style.left 	= windowScrollX+(windowWidth/2 - popupWidth/2) + 'px';
	$('popup').style.top 	= windowScrollY+(windowHeight/2 - popupHeight/2) + 'px';
	showPopup(); //Show the popup

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

/**
 *	Function to hide the popup
 **/
function hidePopup() {
	if (!pageLoaded || popupLocked) return false;
	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 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 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 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';
	}
}

var charscount=0;
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 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;
	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';
}