function sendXmlHttpRequest(handler, handlerParam, method, url, content, headers)
{
    var xmlhttp = (window.XMLHttpRequest ? new XMLHttpRequest : (window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : false));
    if (!xmlhttp)
    {
        return false;
    }
    xmlhttp.open(method, url);
    xmlhttp.onreadystatechange = function()
    {
        handler(xmlhttp, handlerParam);
    };

    if (headers)
    {
        for (var key in headers)
        {
            xmlhttp.setRequestHeader(key, headers[key]);
        }
    }
    xmlhttp.send(content);
    return true;
}

function loadZip(el, targetId, notallOption)
{
    var coid = el.value;

	if (coid != 320)
	{
		displayZip(targetId, false);
	    
		// default country
		if (coid == 0)
	    {
	    	coid = 320;
	    }
	    
		return;
	}
	else
	{
		displayZip(targetId, true);
	}

    var url = './ajax/zip.php?coid='+ coid;
    
    if (notallOption)
    {
    	url += '&notall=1';
    }
    
    if (targetId != '')
    {
	    var target = document.getElementById(targetId);
		target.innerHTML = '';
	    target.options[target.options.length] = new Option('Loading ...', '-1');
		sendXmlHttpRequest(handleZip, target, 'GET', url);
	}
}

function stayOnline()
{
	setTimeout("startOnlineRequest()", 60 * 1000);
}

function startOnlineRequest()
{
	var currentTime = new Date();
	var url = './ajax/online.php?time='+ currentTime.getTime();
	sendXmlHttpRequest(handleOnline, null, 'GET', url);
}

function handleOnline(xmlhttp)
{
    if (xmlhttp.readyState == 4)
    {
        var entries = xmlhttp.responseXML.getElementsByTagName('online');
        for (i = entries.length; i > 0; i--) 
        {
    		var entry = entries[i - 1];
    		var status = entry.firstChild.data;
    		if (status == '1')
    		{
    			stayOnline();
    		}
    	}
    }
}

function displayZip(targetId, bool)
{
	var zipSelect = document.getElementById(targetId);
	if (targetId == '')
	{
		return;
	}
	
	if (bool)
	{
		if (document.getElementById(targetId+'label'))
		{
			document.getElementById(targetId+'label').style.display='block';
		}
		zipSelect.style.display='block';
	}
	else
	{
		if (document.getElementById(targetId+'label'))
		{
			document.getElementById(targetId+'label').style.display='none';
		}
		zipSelect.style.display='none';
		zipSelect.selectedIndex = 0;
	}
}

function handleZip(xmlhttp, target)
{
    if (xmlhttp.readyState == 4)
    {
        var zips = xmlhttp.responseXML.getElementsByTagName('zip');
        var target = target;

        target.innerHTML = '';

        for (var i=0; i < zips.length; i++)
        {
            var label = zips[i].firstChild.data;
            var val = zips[i].getAttribute('id');
            target.options[target.options.length] = new Option(label, val);
        }
    }
}

function popupImage(image)
{
    popUp(image.href);
    return false;
}

function photoChange(id, url, imgtype, size)
{
	var el = document.getElementById(id);
	el.onload = function(){resizeImage(this, size ? size :  2, 'detail');}
	el.src = url;
	document.getElementById('btn_photo'+imgtype).style.display = 'none';
	document.getElementById('btn_photo'+(imgtype == 'soft' ? 'hard' : 'soft')).style.display = 'inline';
	var el = document.getElementById('btn_zoom')
	if (el)
		{ el.href = url; }
	document.getElementById('popup').href = url;
}
function photoPopUp(id, url)
{
	try
	{
		url = document.getElementById(id).src;
	}
	catch(err){}
	window.open(url, '', 'toolbar=no,menubar=no,location=no,directories=no,scrollbars=yes,resizable=yes,status=no,width=800,height=600');
	return false;
}

function popUp(url)
{
    window.open(url, '', 'toolbar=no,menubar=no,location=no,directories=no,scrollbars=yes,resizable=yes,status=no,width=800,height=600');
}

function addFav()
{
	url = 'http://' + window.location.hostname + '/?id=' + projectId;
	title = window.document.title;
	if (window.sidebar) {
		// Mozilla Firefox Bookmark
		window.sidebar.addPanel(title, url, "");
	}
	else if( window.external ) {
		// IE Favorite
		window.external.AddFavorite( url, title);
	}
	else if (window.opera && window.print){
		// Opera
		alert("Please use CTRL + D.");
	}
	else {
		// Mac and other
		alert("Please use CTRL + T, or similar.");
	}
}

function resizeImage(myImg, divide, id) 
{
	temp = document.createElement("img");
	temp.src = myImg.src;

	imgw = temp.width ? temp.width : myImg.width;
	imgh = temp.height ? temp.height : myImg.height;

	myImg.style.display = 'none';
	detailBlock = document.getElementById(id ? id : 'detail');
	w = detailBlock.offsetWidth;
	w = w / divide;
	ratio = imgw > w ? w/imgw : 1;
		myImg.style.width = ratio * imgw + 'px';
		myImg.style.height = ratio * imgh + 'px';
		var el = document.getElementById('btn_zoom');
		if (el)
		{
			el.style.display = 'inline';
			document.getElementById('player').style.height = ratio * imgh + 20 + 'px'; 
		}
	myImg.style.display = 'block';
}


function showSub(id) {
	if (document.getElementById("sub")) {
		mySub = document.getElementById("sub");
		subs = mySub.getElementsByTagName('DIV');
		for (i=0;i<subs.length;i++) {
			subs[i].style.display='none'
		}
		document.getElementById("sub" + id).style.display='block';
	}
}

function restoreSub() {
	showSub(currsub);
}

function goblink(){
	blinkMe = document.getElementById("blink");
	if (blinkMe != null){
		blinkMe.style.visibility = blinkMe.style.visibility != "visible" ? "visible" : "hidden";
		setTimeout("goblink()", 500);
	}
}

function submitMaleForm(selectElement, subElement)
{
	var form = selectElement.form;
	var value = selectElement.value;
	var submit = true;
	
	function addHiddenInput(name, value)
	{
		var input = document.createElement("input");

		input.type = 'hidden';
		input.name = name;
		input.value = value;

		form.appendChild(input);
	}

	function displayCategorySelect(bool, subElement)
	{
		var categorySelect = document.getElementById(subElement);
		
		categorySelect.style.display = bool ? 'inline' : 'none';
	}
	
	// hide category select
	displayCategorySelect(false, subElement);
	
	// write mail
	if (value == 1)
	{
		addHiddenInput('page', 'user');
		addHiddenInput('action', 'mail');
		addHiddenInput('mailaction', 'write');
	}
	// add to friend category
	else if (value == 2)
	{
		addHiddenInput('page', 'user');
		addHiddenInput('action', 'friend');
		addHiddenInput('friendaction', 'add');
		
		// show category select
		displayCategorySelect(true, subElement);
		
		submit = false;
	}
	// ignore
	else if (value == 3)
	{
		addHiddenInput('page', 'profilemale');
		addHiddenInput('action', 'ignore');
	}
	// delete friend(s)
	else if (value == 4)
	{
		addHiddenInput('page', 'user');
		addHiddenInput('action', 'friend');
		addHiddenInput('friendaction', 'delete');
	}
	else
	{
		submit = false;
	}
	
	if (submit)
	{
		form.submit();
	}
}

function submitMaleFormChild(selectElement)
{
	if (selectElement.value)
	{
		var input = document.createElement("input");

		input.type = 'hidden';
		input.name = 'ufcid';
		input.value = selectElement.value;

		selectElement.form.appendChild(input);
		selectElement.form.submit();
	}
}

function checkUncheckAll(theElement) 
{
	var theForm = theElement.form, z = 0;
	for (z = 0; z < theForm.length; z++)
	{
      	if (theForm[z].type == 'checkbox' && theForm[z].name != 'checkall')
      	{
	 		theForm[z].checked = theElement.checked;
      	}
	}
}

function toggle(id) {
	el=document.getElementById(id);
	if (el.style.display == 'block') el.style.display ='none'
	else el.style.display = 'block';
}

function scroll(id) {
	el=document.getElementById(id);
	y = el.offsetParent.offsetTop + el.offsetTop - 10;
	window.scrollTo(0,y);
}

/* custom RSS */
var lastquery;
var query;

function createQuery(id) {
	var form = document.getElementById(id);
	var elements = form.elements;
    var pairs = new Array();
    for (var i = 0; i < elements.length; i++) {
        if ((name = elements[i].name) && (value = elements[i].value) && (elements[i].type != 'radio')) {
            pairs.push(name + "=" + encodeURIComponent(value));
		}
		else if ((name = elements[i].name) && (value = elements[i].value) && (elements[i].checked)) {
			pairs.push(name + "=" + encodeURIComponent(value));
			if (elements[i].value == 'profile') document.getElementById('searchpartner').style.display='block';
			if (elements[i].value == 'video') document.getElementById('searchpartner').style.display='none';
			if (elements[i].value == 'gallery') document.getElementById('searchpartner').style.display='none';
		}
    }
    return pairs.join("&");
}

function getrss(ajax){
	if (ajax.readyState == 4){
		if(ajax.status == 200 || ajax.status==0){
			var response=ajax.responseText;
			document.getElementById('resultlink').value = response;
		}
	else alert("Error: "+ ajax.status +":"+ ajax.statusText);
	}
}

function sendrss(){
	var ajax = (window.XMLHttpRequest ? new XMLHttpRequest() : (window.ActiveXObject ? new ActiveXObject("Microsoft.XMLHTTP") : false));
	if(!ajax){
		alert("Error");
		return true;
	}
	ajax.onreadystatechange= function () {getrss(ajax); } ;
	lastquery = query;
	query = "index.php?page=rss&action=custom&ajax=1&" + createQuery('form-rss');
	if (lastquery != query) {
		ajax.open("GET", query, true);
		ajax.send(null);
	}
	return false
}

function initrss(id) {
	var form = document.getElementById(id);
	var elements = form.elements;
    for (var i = 0; i < elements.length; i++) {
		elements[i].onclick=function(e) {
            sendrss();
		}

	}
}

function display_overlay()
{
	if (navigator.appName.indexOf("Microsoft")!=-1) 
	{
		toppos = 150;
		leftpos = document.body.clientWidth / 2 - 240;
	}
	else
	{
		toppos = 150;
		leftpos = window.innerWidth / 2 - 240;
	}

	var newdiv = document.createElement('div');
	newdiv.setAttribute('id', "overlay");
	newdiv.style.width = 420;
	newdiv.style.height = 420;
	newdiv.style.position = "absolute";
	newdiv.style.left = leftpos + "px";
	newdiv.style.top = toppos + "px";
	newdiv.style.background = "#FFFFFF";
	newdiv.style.border = "4px solid #CC0000";
	newdiv.style.padding = "6px";
	newdiv.className = "box";
	
	var image = document.createElement('img');
	image.src = "front/img/layer.jpg";
	image.height = 400;
	image.width = 400;

	var link = document.createElement('a');
	link.onclick = function(){document.getElementById("overlay").style.display="none"; return false};
	link.href='#';
	link.appendChild(image);
	link.appendChild(document.createElement('br'));
	link.appendChild(document.createTextNode("Fenster schliessen"));
	link.style.textDecoration = "none";

	newdiv.appendChild(link);
	document.body.appendChild(newdiv);
}

function sub_switch(type)
{
	var possible = Array('clip', 'profile', 'video', 'gallery', 'cam');
	for (var i = 0; i < possible.length; i++)
    {
		el = document.getElementById('sub_'+possible[i]);
		el.style.display = 'none';
		el = document.getElementById('tab_'+possible[i]);
		el.className = el.className.replace('curr', '');
    }

	el = document.getElementById('sub_'+type);
	el ? el.style.display = 'block' : 0;
	
	el = document.getElementById('tab_'+type);
	el ? el.className += ' curr' : 0;
	
	el = document.getElementById('submenu');
	el ? el.className = 'contentbox '+type : 0;
}

function displayPlayer(link){
	document.getElementById('video_player').style.display = 'block';
	xxplayer = document.getElementById('VideoMine');
	xxplayer.controls.play();
	window.location.href = window.location.href + "#a_video_player";
	return false;
}

function camOpen(link){
	wnd = window.open(link.href, link.target, 'top='+(screen.height-530)/2+',left='+(screen.width-680)/2+',width=680,height=530,scrollbars');
	if (wnd != null)
	{
		wnd.focus();
		return false;
	}
	return true;
}

function copyToClipboard(s)
{
	if( window.clipboardData && clipboardData.setData )
	{
		clipboardData.setData("Text", s);
	}
	else
	{
		// You have to sign the code to enable this or allow the action in about:config by changing
		user_pref("signed.applets.codebase_principal_support", true);
		netscape.security.PrivilegeManager.enablePrivilege('UniversalXPConnect');

		var clip = Components.classes['@mozilla.org/widget/clipboard;[[[[1]]]]'].createInstance(Components.interfaces.nsIClipboard);
		if (!clip) return;

		// create a transferable
		var trans = Components.classes['@mozilla.org/widget/transferable;[[[[1]]]]'].createInstance(Components.interfaces.nsITransferable);
		if (!trans) return;

		// specify the data we wish to handle. Plaintext in this case.
		trans.addDataFlavor('text/unicode');

		// To get the data from the transferable we need two new objects
		var str = new Object();
		var len = new Object();

		var str = Components.classes["@mozilla.org/supports-string;[[[[1]]]]"].createInstance(Components.interfaces.nsISupportsString);

		var copytext=meintext;

		str.data=copytext;

		trans.setTransferData("text/unicode",str,copytext.length*[[[[2]]]]);

		var clipid=Components.interfaces.nsIClipboard;

		if (!clip) return false;

		clip.setData(trans,null,clipid.kGlobalClipboard);	   
	}
}

function gallery_changePreview(link)
{
	var url = './ajax/gallery.php?action=preview&id='+ link.childNodes[0].id;
	sendXmlHttpRequest(gallery_handleChangePreview, link.childNodes[0].src, 'GET', url);
	return false;
}

function gallery_handleChangePreview(xmlhttp)
{
    if (xmlhttp.readyState == 4)
    {
    	try
    	{
    		var entries = xmlhttp.responseXML.getElementsByTagName('response');
    		for (i = entries.length; i > 0; i--) 
    		{
    			var entry = entries[i - 1];
    			var newimage = entry.firstChild.data;
    			if (newimage != '')
    			{
    				document.getElementById('gallerypreview').src = newimage;
    			}
    		}
    	}
    	catch(err){}
    }
}

function texttoggle(elid)
{
	if (elid != 'data')
	{
		var el = document.getElementById('profiledata');
		if (el)
		{
			el.style.display = 'none';
			document.getElementById('btn_data').className = "button"
		}
	}
	
	if (elid != 'text')
	{
		var el = document.getElementById('profiletext');
		if (el)
		{
			el.style.display = 'none';
			document.getElementById('btn_text').className = "button"
		}
	}
	
	if (elid != 'blog')
	{
		var el = document.getElementById('profileblog');
		if (el)
		{
			el.style.display = 'none';
			document.getElementById('btn_blog').className = "button"
		}
	}

	var el = document.getElementById('profile'+elid);
	if (el)
	{
		el.style.display = 'block';
		document.getElementById('btn_'+elid).className += " imp";
	}
}

function fb_close(url)
{
	var opener = window.opener;
	if (opener)
	{
		opener.location.reload();
		window.close();
	}
	else
	{
		window.location = url;
	}
}

function addtourl(name, value) {
	url = window.location.href;
	if (url.indexOf(name) > 0) {
		var txt = new RegExp("([\&]?)" + name + "=([0-9a-zA-Z]*)");
		url = url.replace(txt, '');
		var txt = new RegExp("([\?]?)" + name + "=([0-9a-zA-Z]*)");
		url = url.replace(txt, '?');
	}
	if (url.indexOf('?')) {
		url += '&' + name + '=' + value;
	} else {
		url += '?' + name + '=' + value;
	}
	window.location = url;
	return false;
}
function addselecttourl(select)
{
	return addtourl(select.name, select.value);
}

$(document).ready(function() {
	$('a#popup').colorbox();
	$('#btn_zoom').colorbox();
	$('#gallerydetailimage').load(function() {
		resizeImage(this, 1, 'galleryimagedetail') 
	});

	if (document.getElementById('showalert'))
	{
		$.nyroModalSettings({
			processHandler: function(settings) {$("object, embed").css("visibility","hidden");},
			endRemove: function(settings) {$("object, embed").css("visibility","visible");}
		});
		$('#showalert').nyroModalManual({
			closeSelector:'.nyroModalClose, .close',
			wrap:{div: '<div id="content"></div>'},
				padding:0,
				zIndexStart: 1000
		});
	}
});
