var yOffset = 0;		// used for resizing the tree
var isDOMLoaded=0;		// used for checking if DOM is loaded
var gFolder=0;			// used to save folder id for some functions, not set by default
var doneInit=false;		// set to true once we run init()
if(!window.location.href.match(/mikeb$/)) {
	DOMReady('init');	// when the DOM is ready, execute init()
}


/**
* when the DOM is fully loaded, execute a function
*
* @f:String		name of function to run
*/
function DOMReady(f) {
	if (document.addEventListener)
		document.addEventListener("DOMContentLoaded",
		function() {
			isDOMLoaded=1;
			eval(f+'();');
		}, false);
	else if (document.all && !window.opera) {
		document.write('<script type="text/javascript" id="contentloadtag" defer="defer" src="javascript:void(0)"><\/script>')
		var contentloadtag=document.getElementById("contentloadtag")
		contentloadtag.onreadystatechange=function() {
			if (this.readyState=="complete"){
	    		alreadyrunflag=1
	    		eval(f+'();');
			}
		}
	}

	window.onload=function() {
		setTimeout("if (!isDOMLoaded) "+f+"();", 0);
	}
}

/**
* show/hide advanced search dialog
*/
function toggleAdvancedSearch() {
	$('searchBox123').style.display=$('searchBox123').style.display=='none'?'':'none';
	return;
	var table=document.getElementById('searchBox');//$$('table.searchBox');
	for(var i=1; i<table.rows.length; i++) {
		table.rows[i].style.display=table.rows[i].style.display=='none'?'':'none';
	}
}

/**
* for advanced search, toggle the "include subfolders" button
*/
function toggleSubfolders() {
	$('subfolders').disabled = !$('current_folder').checked;
}

/**
* when a textbox(o) receives or loses focus
*/
function textfocus(o) {
	o.style.color = '#000000';
	o.select();
}
function textblur(o) {
	o.style.color = '#969696';
}

/**
* to change the language
*/
function changeLang(lang) {
	var url=window.location;
	var re=/([^?]*)(\??[^#]*)#*/
	var match=re.exec(url);
	var base=match[1];
	var params=match[2];
	window.location.href=base+(params==''?'?':(params+'&'))+'lang_id='+lang;
}

/**
* cursor functions
*/
/*function showhandcursor(o) {
	o.style.cursor='pointer';
}
function shownormalcursor(o) {
	o.style.cursor='default';
}*/

/**
* shopping cart functions
*/
function cart_additem(item, qty) {
	qty=(!qty)? 1 : qty;
	document.forms['cart'].elements['cart-action'].value = 'add';
	document.forms['cart'].elements['cart-items'].value = item;
	document.forms['cart'].submit();
}
function cart_remitem(item, qty) {
	qty=(!qty)? 1 : qty;
	document.forms['cart'].elements['cart-action'].value = 'rem';
	document.forms['cart'].elements['cart-items'].value = item;
	document.forms['cart'].elements['cart-qty'].value = qty;
	document.forms['cart'].submit();
}
function updatecart(form) {

}

/**
* drop box functions
*/
function addDropBox(objectid) {
	new Ajax.Request('larissa/cms/data/module/downloadzone/dropbox_ajax.php?dropbox-action=add&objectid='+objectid,
		{
			method:	'get',
			onSuccess:	addDropBoxSuccess,
			onFailure:	addDropBoxFailure
		}
	);
}
function addDropBoxSuccess(response) {
	eval(response.responseText);
	if(success===true) {
		var table=$$('table.dropbox')[0];
		var items=$$('table.dropbox img');
		if(items.length % 3 == 0) {
			table.insertRow(-1);
		}
		var row=table.rows[table.rows.length-1];
		var cell=row.insertCell(-1);
		var a=document.createElement('a');
		a.href='view_object.php?objectid='+objectid;
		var img=document.createElement('img');
		img.src='get_thumb.php?objectid='+objectid;
		img.width='70';
		img.height='52';
		img.border='0';

		a.appendChild(img);
		cell.appendChild(a);
	}
}
function addDropBoxFailure(response) {
	// do nothing
}
function startDropboxDrag(event) {
	if(!ie6) {
		var y=event.pointerY();
		var treetop=eval($('tree').getStyle('top').gsub('px',''));
		yOffset=treetop-y;
		yOffset=yOffset > 0 ? yOffset : 0;

		Event.observe(document,'mousemove',resizeTree);
		Event.observe(document,'mouseup',
			function() {
				Event.stopObserving(document,'mousemove',resizeTree);
				new Ajax.Request('larissa/cms/data/module/downloadzone/saveHeight.php?height='+$('dropbox').getHeight());
			}
		);
	}
}
function resizeTree(event) {
	var y=event.pointerY();
	var treetop=eval($('tree').getStyle('top').gsub('px',''));
	var docheight=document.viewport.getHeight();

	if(y - yOffset > treetop + (docheight-treetop)/3 && y - yOffset < docheight-138) {
		$('dropbox').style.top=(y - yOffset)+'px';
		$('dropbox').style.height=(docheight - y - yOffset)+'px';
		windowResize();
	}
}

/**
* some library functions
*/
function isArray(obj) {
	if (obj.constructor.toString().indexOf('Array') == -1)
		return false;
	else
		return true;
}
function getQueryVariable(variable) {
	var query = window.location.search.substring(1);
	var vars = query.split("&");
	for (var i=0;i<vars.length;i++) {
		var pair = vars[i].split("=");
		if (pair[0] == variable) {
			return pair[1];
		}
	}
	return false;
}

// IE < 7 function to take care of fixed positioning
function IEScroll() {
	var offsetX=document.viewport.getScrollOffsets()[0];
	var offsetY=document.viewport.getScrollOffsets()[1];

	if($('header')&&$('language_bar')&&$('tree')) {
		if($('header').style&&$('language_bar'.style)&&$('tree').style) {
			$('header').style.top		= offsetY+'px';
			$('language_bar').style.top	= offsetY+$('header').getHeight()+'px';
			$('tree').style.top			= offsetY+$('header').getHeight()+$('language_bar').getHeight()+1+'px';
		}
	}
}

function dumpProps(obj, parent) {
   // Go through all the properties of the passed-in object
   for (var i in obj) {
      // if a parent (2nd parameter) was passed in, then use that to
      // build the message. Message includes i (the object's property name)
      // then the object's property value on a new line
      if (parent) { var msg = parent + "." + i + "\n" + obj[i]; } else { var msg = i + "\n" + obj[i]; }
      // Display the message. If the user clicks "OK", then continue. If they
      // click "CANCEL" then quit this level of recursion
      if (!confirm(msg)) { return; }
      // If this property (i) is an object, then recursively process the object
      if (typeof obj[i] == "object") {
         if (parent) { dumpProps(obj[i], parent + "." + i); } else { dumpProps(obj[i], i); }
      }
   }
}

/**
* Shows the AGB dialog box
*
* @folder	the id of the folder that has been clicked
*/
function showAGB(folderid) {
	document.body.style.overflowY='hidden';
	gFolder=folderid;	// set global

	$('agb_text').innerHTML=$('agb_'+folderid).innerHTML;

	$('agb_box').style.width=(document.viewport.getWidth()*0.6)+'px';
	$('agb_box').style.height=(document.viewport.getHeight()*0.6)+'px';
	$('agb_box').style.left=(document.viewport.getWidth()*0.2)+'px';
	$('agb_box').style.top=(document.viewport.getHeight()*0.2)+'px';

	if(ie6)
		$('agb_text').style.width=($('agb_box').getWidth()-80)+'px';
	else
		$('agb_text').style.width=($('agb_box').getWidth()-80)+'px';

	$('agb_text').style.height=($('agb_box').getHeight()-100)+'px';

	$('agb_bg').style.display='block';
	$('agb_box').style.display='block';

	$('sort_by_box').hide();
	$('per_page_box').hide();
}

/**
* AGB has been accepted
*/
function acceptAGB() {
	if(gFolder>-1)
		window.location.href='query_objects.php?folder='+gFolder+'&s=&accept_agb';
	else {
		declineAGB();
		if($('agree'))
			$('agree').checked=true;
	}
}
/**
* AGB has been declined
*/
function declineAGB() {
	document.body.style.overflowY='';
	$('agb_bg').style.display='none';
	$('agb_box').style.display='none';
	$('sort_by_box').show();
	$('per_page_box').show();
	if($('agree'))
		$('agree').checked=false;
}

/**
* Set the pagination and submit form
*/
function setPage(page) {
	page=page>0?page:1;
	document.forms.search.elements.p.value=page;
	document.forms.search.submit();
}

/**
* View an object
*/
function viewObject(id) {
	window.location.href='view_object.php?objectid='+id;
}

/**
* When the page loads, initialize some things
*/
function init() {
	if(!doneInit) {
		doneInit=true;
		// take care of drop box height
		$('dropbox').style.height=$F('dropboxHeightInit')+'px'; // get from form element set by PHP
		$('dropboxBody').style.height=$('dropbox').getHeight()-22+'px';
		$('dropbox').style.top=document.viewport.getHeight()-$('dropbox').getHeight()+'px';

		// take care of tree height
		$('tree').style.height=document.viewport.getHeight()-$('header').getHeight()-$('language_bar').getHeight()-$('dropbox').getHeight()+'px';
		$('treeBody').style.height=document.viewport.getHeight()-$('header').getHeight()-$('language_bar').getHeight()-$('dropbox').getHeight()-22+'px';

		// and whenever the window resizes
		Event.observe(window,'resize',windowResize);

		// message area
		/*var msgbox = document.getElementById('message');
		msgbox.style.display = (msgbox.innerHTML=='')? 'none' : 'block';*/

		// auto-completion
		//new Ajax.Autocompleter('search_text_box','search_hinting','http://media.simovative.de/get_search_words.php');

		// tooltips
		var imgs=$$('img');
		if(window.location.href.match(/mikeb$/)) {
			for(var i=0; i<imgs.length; i++) {
				var x = new Tooltip(imgs[i],'tooltip');
				alert(imgs[i]);
				if(x===false)
					alert(imgs[i]+' '+imgs[i].id);
			}
		}

		// use prototype to take care of mous events
		var elements=$$('a, img, div');
		var events_list=new Array('mouseover','mouseout','mousedown','mouseup','click');
		for(var i=0; i<elements.length; i++) {
			for(var j=0; j<events_list.length; j++) {
				if(elements[i]) {
					if(elements[i].readAttribute) {
						if(elements[i].readAttribute(events_list[j])!=null) {
							if(elements[i].readAttribute(events_list[j]).indexOf) {
								eval("elements["+i+"].observe('"+events_list[j]+"',function(event){"+elements[i].readAttribute(events_list[j])+"});");
							}
						}
					}
				}
			}
		}

		if(!ie6) {
			// make drop-box droppable, but only if above IE6
			Droppables.add('dropboxBody',
			{
				hoverclass:	'dropboxHover',
				onDrop:	function(src,target,event) {
					if(src.readAttribute) {
						addDropBox(src.childElements()[0].readAttribute('id'));
					}
				}
			});
		}

		// call init for local page
		if(self.pageInit)
			pageInit();
	}
};

function windowResize() {
	var treetop=eval($('tree').getStyle('top').gsub('px',''));
	var docheight=document.viewport.getHeight();

	if($('dropbox').getHeight() > 2*(docheight-treetop)/3 && 2*(docheight-treetop)/3 > 138) {
		$('dropbox').style.height=(2*(docheight-treetop)/3)+'px';
	} else if($('dropbox').getHeight() < 138) {
		$('dropbox').style.height='183px';
	}

	$('dropbox').style.top=document.viewport.getHeight()-$('dropbox').getHeight()+'px';
	$('dropboxBody').style.height=$('dropbox').getHeight()-22+'px';
	$('tree').style.height=document.viewport.getHeight()-$('header').getHeight()-$('language_bar').getHeight()-$('dropbox').getHeight()+'px';
	$('treeBody').style.height=$('tree').getHeight()-22+'px';

	if($('agb_bg').style.display=='block') {
		showAGB(gFolder);
	}
}