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

/** Check for default **/
if (typeof Prototype == 'undefined') alert("Prototype is required but is missing");
var IWEBPATH = '/';

var dimmerDensity = 65; //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	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 = '';
var charscount=0;
var forcedShow = false;

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

	systemInit();
	
	//Check for common loader
	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();
}

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

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

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

function callOnLoad() {
	document.onmousemove = function(e) {
		if (!pageLoaded && !forcedShow) return true;
		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();
		}
	}

	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;

	$('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 && !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 (!pageLoaded && !forcedShow) return false;
	if (!document.all) 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 (!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.background 	= 'url('+IWEBPATH+'images/frame/frame_top_left.png)';
	td1.style.behavior	 	= 'url(/iepngfix.htc)';
	td1.width 				= '20';
	td1.height 				= '20';

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

	var td3 = document.createElement('td');
	td3.style.padding 		= '0';
	td3.style.background 	= 'url('+IWEBPATH+'images/frame/frame_top_right.png)';
	td3.style.behavior	 	= 'url(/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('+IWEBPATH+'images/frame/frame_bgnd_left.png)';
	td1.style.behavior	 	= 'url(/iepngfix.htc)';

	var td2 = document.createElement('td');
	td2.id					= 'tblContentTd';
	td2.style.width			= 0;
	td2.style.height		= 0;
	td2.style.padding 		= '0';
	td2.style.background 	= 'black';
	//td2.style.opacity		= 0.75;
	//td2.style.filter		= 'alpha(opacity=75)';
	td2.style.background 	= 'url('+IWEBPATH+'images/frame/frame_bgnd.png)';
	td2.style.behavior	 	= 'url(/iepngfix.htc)';
	td2.innerHTML 			= '<div style="position:relative" id="tblContent"><img src="'+IWEBPATH+'images/preloader.gif" /></div>';
	td2.style.color			= "white";

	var td3 = document.createElement('td');
	td3.style.padding 		= '0';
	td3.style.background 	= 'url('+IWEBPATH+'images/frame/frame_bgnd_right.png)';
	td3.style.behavior	 	= 'url(/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.background 	= 'url('+IWEBPATH+'images/frame/frame_bottom_left.png)';
	td1.style.behavior	 	= 'url(/iepngfix.htc)';

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

	var td3 = document.createElement('td');
	td3.style.padding 		= '0';
	td3.style.background	= 'url('+IWEBPATH+'images/frame/frame_bottom_right.png)';
	td3.style.behavior	 	= 'url(/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 string data 	- The innerHTML
 *	@param bool show	- If true we set popup visible
 **/
function movePopup(l, t) {
	if ((!pageLoaded && !forcedShow) || 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 && !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').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($('tblContentTd').clientWidth);
	popupHeight	= parseInt($('tblContentTd').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;
	}
	
	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
	$('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 && !forcedShow) || popupLocked) return false;
	popupVisible = false;

	//Set the inner part to preloader
	$('tblContent').innerHTML = ''; //<img src="'+IWEBPATH+'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 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';
}