/**
 * PAGEBUTLER JavaScript
 * (c) Copyright 2004-2007 Media Trooper GmbH
 * www.mediatrooper.de
 */

Object.extend(Prototype.Browser, {
     WebKit419: Prototype.Browser.WebKit && (Prototype.BrowserFeatures.XPath),
     WebKit420: Prototype.Browser.WebKit && (!Prototype.BrowserFeatures.XPath),
     IE6:      Prototype.Browser.IE && (typeof window.XMLHttpRequest == "undefined"),
     IE7:      Prototype.Browser.IE && (typeof window.XMLHttpRequest == "object")
});

var initPNGfix = false;
function fixPNGs()
{
	if( initPNGfix==false )
	{
		return false;
	}
	fixPNGsBuddy();
}

// oo->
function goMenu(menu1,menu2,menu3,menu4){
	var url_root = "http://de.samsungmobile.com/";
	if(menu1==null) menu1="";
	if(menu2==null) menu2="";
	if(menu3==null) menu3="";
	if(menu4==null) menu4="";

	document.location = url_root+"gomenu.jsp?menu1=" + menu1 + "&menu2=" + menu2 + "&menu3=" + menu3 + "&menu4=" + menu4;
}
function goHome(){
	document.location = "http://de.samsungmobile.com/index.jsp";
}

// <-oo


function submitAdminForm( sa )
{
	var f = document.getElementById('adminform');
	if( sa )
	{
		f.submitaction.value = sa;
	}
	if( f.getAttribute("ajax") )
	{
		var tas = f.getElementsByTagName("iframe");
		if( tas.length>0 )
		{
			tinyMCE.triggerSave();
		}
		for (i = 0; i < tas.length; i++)
		{ 
			if( tas[i].className=="mceEditorIframe" )
			{
				tinyMCE.execCommand("mceRemoveControl", false, tas[i].id); 
			}
		}
		submitAjaxForm('adminform','ajaxAdminForm');
	}
	else
	{
		f.submit();
	}
}

function pbRedirect( url, pause )
{
	window.setTimeout("document.location='"+url+"';", pause*1000);
}

function getSelectValue( domid )
{
	var s = document.getElementById(domid);
	var i = s.selectedIndex;
	return s.options[i].value;
}

function clearInput(i,s)
{
	if(i.value==s)i.value='';
}
function unclearInput(i,s)
{
	if(i.value=='')i.value=s;
}

function countdown( countdown_id, todatePhpStamp ) 
{
	var todate = todatePhpStamp*1000;
	var sh_seconds, sh_minutes, sh_hours, sh_days, sh_weeks;
	var remain;

	var difference = todate - servertimeClock;
	var seconds = difference / 1000;
	
	if( seconds>0 )
	{
		sh_seconds=0;
		sh_minutes=0;
		sh_hours=0;
		sh_days=0;
		sh_weeks=0;
	}
	
	sh_weeks = Math.floor(seconds / 60 / 60 / 24 / 7);
	remain = seconds - (sh_weeks * 7 * 24 * 60 * 60);
	sh_days = Math.floor(remain / 60 / 60 / 24);
	remain = remain - (sh_days * 24 * 60 * 60);
	sh_hours = Math.floor(remain / 60 / 60);
	remain = remain - (sh_hours * 60 * 60);
	sh_minutes = Math.floor(remain / 60);
	remain = remain - (sh_minutes * 60);
	sh_seconds = Math.floor(remain);
	
	if (document.getElementById(countdown_id+'_weeks')) { document.getElementById(countdown_id+'_weeks').innerHTML = sh_weeks; }
	if (document.getElementById(countdown_id+'_days')) 
	{ 
		document.getElementById(countdown_id+'_days').innerHTML = sh_days;
		if(sh_days<1)
		{
			if (document.getElementById(countdown_id+'_days_hider')) 
			{
				// tage ausblenden, weil nur noch max 24 std
				document.getElementById(countdown_id+'_days_hider').style.display='none';
			}
		}
		else if(sh_days==1)
		{
			if (document.getElementById(countdown_id+'_days_plural')) 
			{
				// plural ausblenden
				document.getElementById(countdown_id+'_days_plural').style.display='none';
			}
		}
	}
	if (document.getElementById(countdown_id+'_hours')) { document.getElementById(countdown_id+'_hours').innerHTML = sh_hours; }
	if (document.getElementById(countdown_id+'_minutes')) { document.getElementById(countdown_id+'_minutes').innerHTML = ((sh_minutes<10)?'0'+sh_minutes:''+sh_minutes); }
	if (document.getElementById(countdown_id+'_seconds')) { document.getElementById(countdown_id+'_seconds').innerHTML = ((sh_seconds<10)?'0'+sh_seconds:''+sh_seconds); }
}

function updateServertimeClock()
{
	servertimeClock+=1000;
}

var userInfoBlock = false;
var cachedUserInfos = new Hash();
function showUserInfo( element, user_id )
{
	var parentElement = $(element);
	if( userInfoBlock==false )
	{
		userInfoBlock = new Element("div",{'class':'userinfo'});
		userInfoBlock.observe('mouseover',function(){
			userInfoBlock.mouseIsOver = true;
		});
		userInfoBlock.observe('mouseout',function(){
			userInfoBlock.mouseIsOver = false;
			window.setTimeout(function(){
				if( userInfoBlock.mouseIsOver==false )
				{
					userInfoBlock.hide();
				}
			},200);
		});
		$('flowingbody').insert(userInfoBlock);
	}
	if( Prototype.Browser.IE6 )
	{
		var left = Event.pointerX(event);
		var top = Event.pointerY(event);
	}
	else
	{	
		var vO = parentElement.viewportOffset();
		var sO = document.viewport.getScrollOffsets();
		var left = vO.left+sO.left+25;
		if( left>(document.viewport.getDimensions().width-300) )
		{
			left = vO.left+sO.left-(userInfoBlock.getWidth()+25);
		}
		var top = vO.top+sO.top+parentElement.getHeight()-5;
		var h = 270; //userInfoBlock.down(".bg_small").getHeight();
		if( top>(document.viewport.getDimensions().height+sO.top-h) ) //userInfoBlock.getHeight()
		{
			top = vO.top+sO.top-h;
		}
	}
	userInfoBlock.setStyle({
		'left':	(left)+'px',
		'top':	(top)+'px'
	});
	parentElement.setStyle({'cursor':'default'});
	parentElement.observe('mouseout',function(){
		userInfoBlock.mouseIsOver = false;
		window.setTimeout(function(){
			if( userInfoBlock.mouseIsOver==false )
			{
				userInfoBlock.hide();
			}
		},200);
	});
	userInfoBlock.mouseIsOver = true;
	if( cachedUserInfos.get(user_id) )
	{
		userInfoBlock.update( cachedUserInfos.get(user_id) );
		userInfoBlock.show();
	}
	else
	{
		userInfoBlock.update('<div class="ajaxloading"><img src="/img/loading.gif" width="24" height="24" /></div>');
		userInfoBlock.show();
		new Ajax.Request('/users/info/'+user_id, {
			asynchronous:true, 
			evalScripts:true, 
			onSuccess: function(transport) {
				    if (transport.responseText.indexOf("USER:"+user_id)!=-1)
				    {
				    	userInfoBlock.update(transport.responseText);
				    }
				    cachedUserInfos.set(user_id,transport.responseText);
				  }
		});
	}
}


function showMedal( element, medal_src )
{
	var parentElement = $(element);
	var icon = parentElement.down("img");
	if( !icon )
	{
		return false;
	}
	var over = parentElement.down(".over");
	if( !over )
	{
		over = new Element("div",{'class':'over','style':'position:absolute;width:70px;height:90px;z-index:88888'});
		over.update(new Element("img",{'src':medal_src,'width':'70','height':'90','alt':'','title':icon.readAttribute('title')}));
		parentElement.insert(over);
	}
	over.show();
	icon.hide();
	parentElement.setStyle({'cursor':'default'});
	parentElement.observe('mouseout',function(){
		over.hide();
		icon.show();
	});
}

/* 
var medalFlowBlock = false;
function showMedal( element, medal_src )
{
	var parentElement = $(element);
	if( medalFlowBlock==false )
	{
		medalFlowBlock = new Element("div",{'class':'medalflow','style':'position:absolute;width:70px;height:90px;z-index:88888'});
		$('flowingbody').insert(medalFlowBlock);
	}
	medalFlowBlock.update(new Element("img",{'src':medal_src,'width':'70','height':'90','alt':''}));
	if( Prototype.Browser.IE6 )
	{
		var left = Event.pointerX(event);
		var top = Event.pointerY(event);
	}
	else
	{
		var vO = parentElement.viewportOffset();
		var sO = document.viewport.getScrollOffsets();
		var left = vO.left+sO.left-Math.round(medalFlowBlock.getWidth()/4);
		var top = vO.top+sO.top+parentElement.getHeight()+10;
		if( top>(document.viewport.getDimensions().height+sO.top-100) ) //userInfoBlock.getHeight()
		{
			top = vO.top+sO.top-90-10;
		}
	}
	medalFlowBlock.setStyle({
		'left':	(left)+'px',
		'top':	(top)+'px'
	});
	medalFlowBlock.show();
	parentElement.setStyle({'cursor':'default'});
	parentElement.observe('mouseout',function(){
		medalFlowBlock.hide();
	});
}*/


function reloadLogin()
{
	ajaxRemoteFunctionTimed('userinfo', '/users/login',1500);
}

/**
 * AJAX
 */

function submitAjaxForm(formId,updatedivid)
{ 
	var actionurl = document.getElementById(formId).action;
	new Ajax.Updater(updatedivid, actionurl, {asynchronous:true, evalScripts:true, parameters:Form.serialize(formId), requestHeaders:['X-Update', updatedivid]}) 
}
function ajaxRemoteFunction(domid, url)
{
	new Ajax.Updater(domid,url, {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', domid]});
}
function ajaxRemoteFunctionTimed(domid, url, tt)
{
	window.setTimeout("ajaxRemoteFunction('"+domid+"','"+url+"')", tt);
}
function doAction(domid, url)
{
	$(domid).update('<div class="ajaxloading"><img src="/img/loading.gif" width="24" height="24" /></div>');
	new Ajax.Updater(domid,url, {asynchronous:true, evalScripts:true, requestHeaders:['X-Update', domid]});
}
function keyPressHandler(e, domid, url) 
{
	return keyPressHandlerFunc(e, "ajaxRemoteFunction('"+domid+"', '"+url+"')");
}
function keyPressHandlerFunc(e, func) 
{
	var kC  = (window.event) ?    // MSIE or Firefox?
		event.keyCode : e.keyCode;
	var Esc = (window.event) ?   
		27 : e.DOM_VK_ESCAPE // MSIE : Firefox
	//alert(kC);
	if(kC==Esc)
	{
		window.setTimeout(func, 10);
	}
	return true;
}

function openNavi( divid, aid )
{
	if( divid=='' ) 
	{
		return true;
	}
	var h = $(divid).getHeight();
	$(divid).setStyle({
		height: h+'px',
		overflow: 'hidden'
	});
	$(divid).update('<div class="ajaxloading"><img src="/img/loading.gif" width="24" height="24" /></div>');
	//new Effect.BlindUp(divid, {duration: 0.5});
	//ajaxRemoteFunction( divid, a.href );
	new Ajax.Updater(divid, $(aid).href+"?ajax="+Math.random() , {
							asynchronous:true, 
							evalScripts:true, 
							requestHeaders:['X-Update', divid], 
							onComplete:completeNaviRequest 
						});
	var e = $(aid).up(1).down();
	do
	{
		e.removeClassName('active');
	} while( e = e.next() );
	$(aid).up().addClassName('active');
	return false;
}

function openMainNavi( divid, aid )
{
	var r = openNavi( divid, aid );
	redrawNavigation();
	return r;
}

function completeNaviRequest( t )
{
	var container = t.request.container['success'];
	//new Effect.BlindDown(container, {duration: 0.5});
	$(container).setStyle({
		height: 'auto',
		overflow: 'auto'
	});
}

function redrawNavigation()
{
	var e = $('navigation').down('li');
	do
	{
		if( e.hasClassName('active') )
		{
			e.down('div.off').hide();
			e.down('div.on').show();
		}
		else
		{
			e.down('div.off').show();
			e.down('div.on').hide();
		}
	} while( e = e.next('li') );
}

function submitVoting()
{
	submitAjaxForm('votingForm','votingAjax');
}

function submitTestresult()
{
	submitAjaxForm('testResultForm','checktestAjax');
}

function formatNumber(num, decpoint, sep) 
{
  // check for missing parameters and use defaults if so
  if (arguments.length == 2) {
    sep = ".";
  }
  if (arguments.length == 1) {
    sep = ".";
    decpoint = ",";
  }
  // need a string for operations
  num = num.toString();
  var negative_prefix = "";
  // check for negative value
  if( num.charAt(0)=='-')
  {
  	num = num.slice(1);
  	negative_prefix = "-";
  }
  // separate the whole number and the fraction if possible
  a = num.split(decpoint);
  x = a[0]; // decimal
  y = a[1]; // fraction
  z = "";


  if (typeof(x) != "undefined") {
    // reverse the digits. regexp works from left to right.
    for (i=x.length-1;i>=0;i--)
      z += x.charAt(i);
    // add seperators. but undo the trailing one, if there
    z = z.replace(/(\d{3})/g, "$1" + sep);
    if (z.slice(-sep.length) == sep)
      z = z.slice(0, -sep.length);
    x = "";
    // reverse again to get back the number
    for (i=z.length-1;i>=0;i--)
      x += z.charAt(i);
    // add the fraction back in, if it was there
    if (typeof(y) != "undefined" && y.length > 0)
      x += decpoint + y;
  }
  return negative_prefix + "" + x;
}

function countChars( id, max )
{
	var v = $(id).getValue();
	var l = v.length;
	var s = max - l;
	if(s<0)
	{
		s = 0;
		$(id).value = v.substr(0,max);
	}
	$(id+'Length').innerHTML = s;
}

var listwalklimit = 5;
var searchfield = null;
var missionsearchword = "";
var lastmissionsearchid = 1;

function listwalk(divid,limit,page)
{
	listwalklimit = limit;
	lastmissionsearchid++;
	var h = $(divid).getHeight();
	if( $(divid).getStyle("overflow")!="hidden" )
	{
		$(divid).setStyle({
			height: h+'px',
			overflow: 'hidden'
		});
	}
	var onlygenius = 0;
	if( $('onlygeniuscheckbox') )
	{
		if( $('onlygeniuscheckbox').checked )
		{
			onlygenius = 1;
		}
	}
	$(divid).update('<div class="ajaxloading"><img src="/img/loading.gif" width="24" height="24" /></div>');
	//ajaxRemoteFunction(divid, '/missions/listing/'+limit+'/'+page);
	if( searchfield && searchfield.istest )
	{
		var url = '/missions/listing_test/'+limit+'/'+page;
	}
	else
	{
		var url = '/missions/listing/'+limit+'/'+page;
	}
	new Ajax.Request(url, {
		parameters: { 	'searchword': missionsearchword,
						'id': lastmissionsearchid,
						'onlygenius': onlygenius
					},
		asynchronous:true, 
		evalScripts:true, 
		onSuccess: function(transport) {
			    if (transport.responseText.indexOf("SEARCH:"+lastmissionsearchid)!=-1)
			    {
			    	$(divid).update(transport.responseText);
			    	$(divid).setStyle({
						height: 'auto',
						overflow: 'auto'
					});
			    }
			  }
	});
}

function onChangeOnlybox()
{
	listwalk('missionlisting',listwalklimit,1);
}

function onChangeMissionSearch()
{
	// suchen
  	var s = searchfield.realvalue;
  	if( s.length>2 )
  	{
 	 	if( s!=missionsearchword )
 	 	{
 	 		// neues suchwort
 	 		missionsearchword = s;
 	 		listwalk('missionlisting',listwalklimit,1);
 	 	}
  	}
  	else if(missionsearchword!="")
  	{
  		missionsearchword = "";
 	 	listwalk('missionlisting',listwalklimit,1);
  	}
}

function createRealButton( element, src_over, src_down, onclick )
{
	var img_normal = new Image();
	img_normal.src = element.src;
	var img_over = new Image();
	img_over.src = src_over;
	var img_down = new Image();
	img_down.src = src_down;
	var mousedown_seconds = 0;
	element.observe('mousedown', function(){
		element.src = img_down.src;
		mousedown_seconds = new Date().getTime();
	});
	element.observe('mouseover', function(){
		element.src = img_over.src;
	});
	element.observe('mouseout', function(){
		element.src = img_normal.src;
	});
	element.observe('mouseup', function(){
		if( new Date().getTime()-mousedown_seconds < 300 )
		{
			setTimeout(function(){element.src=img_normal.src;}, 200);
		}
		else
		{
			element.src = img_normal.src;
		}
		onclick();
	});
}

function makeMissionSearch( divid, limit, istest )
{
	missionsearchword = "";
	listwalklimit = limit;
	searchfield = new Element("input",{'type':'text','class':'search'});
	searchfield.istest = istest;
	searchfield.onChangeHandle = function() { onChangeMissionSearch(); };
	var searchform = new Element("form",{'class':'applesearch','action':'','method':'post'});
	var fieldset = new Element("fieldset");
	var label = new Element("label",{'for':searchfield.identify()}).update("suchen");
	fieldset.insert(label);
	fieldset.insert(searchfield);
	searchform.insert(fieldset);
	
	if( istest!="test" )
	{
		var checkbox = new Element("input",{'id':'onlygeniuscheckbox','type':'checkbox','class':'applesearch_onlybox'});
		var checkbox_label = new Element("label",{'for':'onlygeniuscheckbox','class':'applesearch_onlybox'}).update("nur Genius Missionen");
		checkbox_label.insert(new Element("img", {'src':'/img/genius_text_grey.gif','width':'14','height':'13','alt':'Genius'}));
		checkbox.observe('click', function() { onChangeOnlybox(); } );
		$(divid).insert(checkbox);
		$(divid).insert(checkbox_label);
	}
	
	$(divid).insert(searchform);
	
	applesearch.init(searchform.identify());
}

function showTextPage(p,t,freeMapOnLastPage)
{
	p = Number(p);
	t = Number(t);
	if(p>1)
	{
		$('textpage'+(p-1)).hide();
	}
	$('textpage'+p).show();
	if( p==t && freeMapOnLastPage=="1" )
	{
		freeMap();
	}
}


						
