

var isRotating = true;

var pauseJob;
var mouseOutJob;
var toggleButtonElementName = "toggleButton";

var rotateUs 			= Array();
var rotateUs_current    = 0;
var lastRotatedElements = Array();
var lastRotatedElement = 0; 	// starts with best hit
var distance 			= "";
var distanceResult 		= "";
var currentSearch 		= "";
var currentPageAdImpressions=0;

/* config */
var conf_alternateResultNumber = 6;  // no marker on map -> show that amount in close distance
var conf_minBranchesDisplayed  = 1;  // if less, conf_alternateResultNumber will be used
var conf_maxBranchesDisplayed  = 6;  // how many are displayed at the same time
var conf_maxBranchesToLoad     = -1;  // how many rotate through
var conf_rotation_delay 	   = 7000; // ms

// control of branches
var branchDiv = "giveInfo";

/* /config */

/* req. vars */

var activeBranch;
var job;
var newfid;
var lastRotatedElements = Array();
var removedRotatedElem = null;
  var debugMode = false; // set in map.js

/* css selectors */
var uid1_css_playbutton_play_class = "uid1_css_playbutton_play";
var uid1_css_playbutton_pause_class = "uid1_css_playbutton_pause";

/* /vars */



/*
 *  Main Functions
 */
 

 function traqUserImpression()
 {
   if(currentPageAdImpressions<10)
   {
    traq('uid1/AdImpressions/frequencyMaxTen/');
   }
   else
   {
   traq('uid1/AdImpressions//frequencyAboveTen/');
   }
   currentPageAdImpressions++;
 }

function startRotationIfNoEfid()
{
        if(   (typeof(efid) =="number" ||  typeof(efid) =="string") )
        {  
        }
        else
            startRotation();
}
function reloadMapIfNoEfid()
{
        if(   (typeof(efid) =="number" ||  typeof(efid) =="string") )
        {
        }
        else
            reloadMap();
}

function startRotation()
{
	isRotating = true;
	if($('toggleButton')) $('toggleButton').removeClassName(uid1_css_playbutton_play_class);

	if(debugMode)
		console.debug("starting");

	doRotation();
}

function doRotation( )
{


	if(isRotating==true)
	{
		rotateLocaleBranches()
	}

	try { clearTimeout(job); }
		catch (e) {}

	job = setTimeout("doRotation()",conf_rotation_delay );
}



function stopRotation()
{
	isRotating = false;
	if($('toggleButton')) $('toggleButton').addClassName(uid1_css_playbutton_play_class);

	if(debugMode)
		console.debug("stopping  ");

	try {
		clearTimeout(job);
	} catch (e) {} // isRotating = false;


}

function pauseRotation(sec )
{
	isRotating = false;
	if($('toggleButton')) $('toggleButton').addClassName(uid1_css_playbutton_play_class);

	if(debugMode)
		console.debug("pausing for "+sec+"  ");


	  // normal job

	pauseJob = setTimeout("continueRotation()", sec);


}

function continueRotation( )
{   // maybe kill previos job to prevent multiple actions in a short time, like mouseover on navi buttons
	 //if(typeof(jobToClear)!="undefined")
	 //{
	 //	try{ clearTimeout(jobToClear); alert("cleared continueRotation job");  }
	 //	catch (e) { }
	 //}  else alert(typeof(jobToClear));

	isRotating = true;
	if($('toggleButton'))
		$('toggleButton').removeClassName(uid1_css_playbutton_play_class);

	if(debugMode)
		console.debug("continueRotation");

	doRotation();
}

function toggleRotation()
{
	if(isRotating==true)
	{
		stopRotation();
	}
	else
	{
		startRotation();
	}
}

function mouseoutRotation(sec)
{

	 	try{ clearTimeout(mouseOutJob); dd("cleared mouseout");   }
	 	catch (e) { }
	    mouseOutJob = setTimeout("continueRotation()", sec);

}






/* @title handleLoadingSuccess
 * @param transport Str (rpc-answer)
 */

function handleLoadingSuccess(transport)
{

    stopRotation(); // stop rotation previous to the new ads
	//$("askPlz").hide();
	//if(!PlzList_isScaled)
	//{	new Effect.Scale("Plz_wrap",140,{scaleX: false,scaleContent: false});
	//PlzList_isScaled = true;
	//}
	dd("nach handleload: "+rotateUs.join(", "));
	// re-init vars based on that result
	setTimeout("prepareRotation()",400);

	//var pre = "<p style=''><img src='gfx/ico/accept.png' alt='erfolgreich' /></p>"

	$("giveInfo").update(transport.responseText);
    if(doHighlightNearestBranch) // update button which is activated by load
    	stopRotation();
    new Effect.Appear("giveInfo",{duration:0.7});
    //highlightFID(first);

    dd('loaded, rotating starting is: '+!doHighlightNearestBranch+" (isrotating: "+isRotating+")");
    /* new on 25 aug 09 - biz
	*  advertizer could deliver the wrong ad to a coordinate (multiple with same lat/lng
	*  , this takes the desired FID instead
	*  of the first given by rotateUs[]
	*/
	if(doHighlightNearestBranch && currentMarker._options['id'] != rotateUs[0])
	{
	   dd("RotateUs[0] is '"+rotateUs[0]+"' - WRONG.: currentMarker is '"+currentMarker._options['id']+"'" );
		var overridden =  showFid(currentMarker._options['id']);

	}
	else dd("RotateUs[0] is '"+rotateUs[0]+"' and it's the desired: currentMarker "+currentMarker._options['id']+", highlightNearest:"+doHighlightNearestBranch );


	/* end */

    if(doHighlightNearestBranch)
    {

    	 doHighlightNearestBranch = false;
    }
    else
    	{  pauseRotation(5000);

    	}
}

function prepareRotation()
{
	lastRotatedElements = Array();
    removedRotatedElem = null;

    // shuffle branches

    dd(("rotateUs org. "+rotateUs.length+": "+rotateUs.join(', ')));

    var first = rotateUs.clone();
    first = first.shift();
    if(doHighlightNearestBranch) // start at first branch
    {
    	var firstBranch = rotateUs.shift();
    	rotateUs.shuffle();
    	rotateUs.unshift(firstBranch);
    	delete(firstBranch);

    }
    	else
    		{   var first1 = rotateUs.shift(); // first is already shown
    			rotateUs.shuffle();
    			rotateUs.push(first1);
    		}
 	dd("rotateUs after shuffle.: "+rotateUs.join(', '));
}


 function ddx()
 {
 	dd("tempMarkers: "+temporaryMarkers[1].length+", rotateUs: "+rotateUs.length+" ("+rotateUs+")");
 }

 /*
  * @title
  * @descr
  */


function rotateLocaleBranches()
{
	newfid = false;
	if(isRotating)
	{  //
	if(rotateUs[rotateUs_current]==null)
	{	if(debugMode)
			console.info("rotateUs at "+rotateUs_current+" is null, rotateUs.length is "+rotateUs.length+",resetting to 0");
		rotateUs_current = 0;
	}

	// existing key, but does corrosponding elem exist?
	if($('fid'+rotateUs[rotateUs_current]+"Button")==null)
	{	if(debugMode)
			console.info("Element Fid"+rotateUs[rotateUs_current]+"Button does not exist, skipping");
        removeHighlighting();
       // rotateLocaleBranches();
	}
	else
	{
		newfid = rotateUs[rotateUs_current];
		removedRotatedElem = null;

		if(lastRotatedElements.length==conf_maxBranchesDisplayed) // got ex. 3, rem. most old one
		{
			removedRotatedElem = lastRotatedElements.shift();
		}
		lastRotatedElements.push(newfid); // add the new one

	    //branches_setActiveButtonByFID(newfid);
	    if(removedRotatedElem!=null)
	    {
	    	$('fid'+removedRotatedElem+"Button").hide();
	    	$('fid'+removedRotatedElem+"Button").up().hide();
	    }


		if($('fid'+newfid)!=null)
		{
		 $('result1').hide();
		$('result1').update($('fid'+newfid).up().innerHTML+"<br class='clear' />");
		$('result1').show(); // appear
		traqUserImpression();
		branches_buttons_render(newfid);
		activeBranch = newfid;
		}
			else
			{ dd("could not load "+newfid);

			}

	}

	rotateUs_current++ ; // maybe skipped broken element
	}
	return true;
}

function branches_buttons_render(newfid)
{
	if(debugMode)
		console.debug("rotating these: "+lastRotatedElements.join(', '));
	var foundError = false;
	var i = 1;
	lastRotatedElements.each( function(s) {
	if($('fid'+s+'Button')==null)
	{	if(debugMode)
			console.warn("button is null: fid"+s+", param newfid: "+newfid);
		foundError = true;
	}
	else
	{

		//var to = $('uid1_h'+i);
		$('fid'+s+'Button').up().show();
		 $('fid'+s+'Button').show();
		// content = $('fid'+s+'Button').up().innerHTML;
		 //to.update(content).appear();;

	}
	 	i++;
	});
	//hightlightFID(newfid,false);
	if(!foundError && newfid!=undefined)
		branches_setActiveButtonByFID(newfid);
	else  {
		if(debugMode)
			console.error("could't display "+newfid);
	}
}


// branches items event-handlers


 function branches_setActiveButtonByFID(newfid,fromElement)
 {
 	if (typeof fromElement == "undefined")
     fromElement = null;

 	if(newfid!='activeBranch')
 	{	$('fid'+activeBranch+"Button").removeClassName("agenturLinkActive");
 		$('fid'+newfid+"Button").addClassName("agenturLinkActive");
 		highlightFID(newfid,false);
 	}
 		return false;
 }


 // the outer element
 function uid1Button_mout(el)
 {
 }


 function uid1Button_mover(elem,newfid)
 { 	if(true) //activeBranch!=newfid // no flickering if same content
 		branches_setActiveButtonByFID(newfid,elem);
 }

 function uid1Button2_mclick(fid)
 { handleActiveBranchClick(fid,this,fid); return false; }

 // the inner element

 function uid1Button2_mover(fid,el)
 { // $command

 	if(true) // activeBranch!=fid //  no flickering if same content
 	{
 	 var destinationDiv = $('result1');
 	 destinationDiv.hide();
 	 destinationDiv.update($('fid'+fid).innerHTML);
 	 Effect.Appear('result1',{duration:0.3});
    handleActiveBranch(fid,el,fid);
    highlightFID(fid);

   } else {
   //	if(debugMode)
   	//	console.info("not switching "+activeBranch+" with "+fid);
   }
   return false;
  }

  function uid1Button2_mout(fid,el)
 { // $command

 	 //var jobRot = window.setTimeout("continueRotation('mout')",200);

     mouseoutRotation(3000 );

   return false;
  }

// further methods



function goLvm(s,isId,name)
{
	//new Effect.toogle("askPlz")
	//on("giveInfo");
	giveInfo(s,isId,name);
}

function goLvm2(id,name)
{
   if(debugMode)
   {
   		console.info("golvm2 mit "+id+" und "+name);
   }
   currentSearch = name;

   suche(false,id);
   //goLvm(id,true,name);

}



function handleActiveBranch(wceid,elem,fid)
{
	if(wceid!=activeBranch)
	{
		$('fid'+activeBranch+"Button").removeClassName("agenturLinkActive");
		$('fid'+fid+"Button").addClassName("agenturLinkActive");
		activeBranch = fid;
		stopRotation();
		highlightFID(fid,false);
	}
	//return false;
}
function handleActiveBranchClick(wceid,elem,fid)
{
	if(wceid!=activeBranch)
	{
		$('fid'+activeBranch+"Button").removeClassName("agenturLinkActive");
		$('fid'+wceid+"Button").addClassName("agenturLinkActive");
		activeBranch = fid;
		stopRotation();
		highlightFID(fid,true);
	}
	return false;
}





// load correct branches  // maybe use that efid
function loadAdsByLocation(lat,lon,efid)
{  
	if(efid=='undefinded' || efid==false || efidPreselectionDone )
		efid = false;
	//var limit = ((temporaryMarkers[1].length)<conf_minBranchesDisplayed)?conf_maxBranchesToLoad:temporaryMarkers[1].length;
	//if(limit>conf_maxBranchesToLoad)
	 //	limit = conf_maxBranchesToLoad;

	 // use the efid once
	 var efidStr = (efid)?"&efid="+efid+"":"";
	 if(efid) efidPreselectionDone = true;
	// console.log(temporaryMarkers);
	/*
	 if(typeof(temporaryMarkers)=="undefined" && temporaryMarkers[1].length==0)
    var limit = 0;
    else
	 var limit = (parseInt(conf_maxBranchesToLoad>1)?conf_maxBranchesToLoad:temporaryMarkers[1].length);
*/
	 var limit = 0;
	 stopRotation();
	    var bounds = map.getBounds();
		var btop =  (bounds.getNorthEast().lat());
		var bright =  (bounds.getNorthEast().lng());
		var bbottom =  (bounds.getSouthWest().lat());
		var bleft =  (bounds.getSouthWest().lng());

	 new Ajax.Request("/ajax/BoundarySearch?top="+btop+"&bottom="+bbottom+"&right="+bright+"&left="+bleft+"&limit="+limit+efidStr,
 	 {
		    method:'get',
		    onCreate: function(transport)
		    {  
		    	$('auskunft_result1_loading').show();
		    },
		    onSuccess: function(transport)
		    {  
		         $('auskunft_result1_loading').hide();
		         traq('/uid1/requestDone');
		         
		    	 dd("handleLoadingS: "+rotateUs.join(", "));
		    	 handleLoadingSuccess(transport);

		    }
 	 });
}





function giveInfo(s,isId,name)
{
	if(isId==true) var param = "locid";
	else var param = "q";

 	new Ajax.Request("ajax/getBranches.php?"+param+"="+s+"&name="+name,
 	{
		    method:'get',
		    onSuccess: function(transport)
		    {
		    	handleLoadingSuccess(transport);

		    }
 	});
}


	function suche(isPlz,name)
	{

	 dd("golvm2 (suche) mit  isPlz="+isPlz+" nach "+name);

   // get an distanceResult object
	 	if(true)
	 	{	k = $('form_k').value;
	 		if(name==false)
			{ 	name = document.forms.submitplz.plz.value;
			 	currentSearch = name;
			}
			 getDistance(name,k,isPlz) ; // to = k
	 	}
	 }




	/*
	 * @descr fills distanceResult with data to the next stva
	 */
	function getDistance(from,to,isPlz)
	{
		 if(debugMode)
		 	console.info("call dist with id "+from+" to "+to);
		 var plzStr =  (isPlz)?"&type=plz":"";

		 new Ajax.Request("ajax/getDistance.php?from="+from+"&to="+to+plzStr,
 		{
		    method:'get',
		    onSuccess: function(transport) {

		     //$("askPlz").hide();
//  			if(!PlzList_isScaled)
//  			{	new Effect.Scale("Plz_wrap",140,{scaleX: false,scaleContent: false});
//		    	PlzList_isScaled = true;
//  			}
  			  distance =  transport.responseText;

  			  if(debugMode)
  			  		console.info("getDistance liefert: "+distance);
  			  if(distance!="false" && distance!='')
  			 {

  			  //distance = secureJSON(distance); // handled by prototype
  			  if(distance!==false)
  			  {
  			  distanceResult =  distance.evalJSON(true); // "sameArea, nearArea"
 			  distance = false;
  			  if(debugMode)
					console.info("distanceresult nach suche(): "+distanceResult);

			  sucheWithDistance(from,isPlz);

  			  } else {} // TODO: implement malicious json handling mechanism
  			 }
  			 	else {
  			 		if(debugMode)
  			 			console.info("failed parsing json");
  			 		 suche_showFailed(from,isPlz);
  			 	}

		    }
		  });
	}

 function secureJSON(str)
 {
 		if (str.substr(0,2) == "/*") // !
  			 	 return str.substring(2, str.length - 2);
  		return false;
 }

 function suche_showFailed(str,isPlz)
 { //alert("Suche nach "+str+" schlug fehl!");
 	var plzStr = (isPlz)?"der PLZ ":"";
 	$('auskunft_suchErgebnis').update("<p>Die Suche nach "+plzStr+str+" erbrachte keinen Treffer.</p>").appear();
 }

	/*
	 *
	 */
	function sucheWithDistance(name,isPlz)
	{   // alert("doing it");
		 //("distance from "+name+" nach "+k+" berechnet als: "+distanceResult.distance);
		dd("suche with distance beginning with "+name+" and isPlz="+isPlz);
		//var loadingBox = "auskunft_sucheWaiting";

		if(isPlz)
			goLvm(document.forms.submitplz.plz.value,false,document.forms.submitplz.plz.value);

		 $('auskunft_ortsauswahl_suche').hide();
		 $('auskunft_ortsauswahl_suchergebnis_tab').addClassName("auskunft_suche_tab_active");
		 $('auskunft_ortsauswahl_suche_tab').removeClassName("auskunft_suche_tab_active");
		$('auskunft_sucheWrapper').show();
		$('auskunft_sucheLoading').appear();
		$('auskunft_suchErgebnis').hide();

		 var showResult = setTimeout("suche_output(currentSearch,distance)", 1500);
		dd("moving map");
		moveMapBySearchResult(distanceResult.sameArea[0].lat,distanceResult.sameArea[0].lon);


	}


	function moveMapBySearchResult(lat,lon)
	{ 	 if(map.getZoom()<11)
	     map.setZoom(11);
		 map.panTo(new GLatLng(lat,lon));
	}

	function suche_output(name)
	{ //var  box = "auskunft_suchErgebnis";

		var myDist = "";
		if(!isNaN( parseFloat( distanceResult.sameArea[0].distance ) ))
			myDist = "(Entfernung: ~"+Math.round(distanceResult.sameArea[0].distance/0.00734)+"km)";
 		else { }
			$('auskunft_sucheLoading').hide();
		var erg = '<br />Zulassungsstellen in <strong>'+k+'</strong> ab '+name+' Zentrum<div style="padding: 5px;  ;"><a href="javascript:void(0)" onclick="$(\'giveInfo\').scrollTo();clickInfoBox('+distanceResult.sameArea[0].id+');return false;">Zulassungsstelle '+distanceResult.sameArea[0].elementTitle+'</a> <span style="font-size:0.9em">'+myDist+'</span> ';

		if(distanceResult.nearArea)
		{
			erg += "<p style='text-align:left'><br /><strong>In der Umgebung von "+name+":</strong>";

			for(var i = 0; i<distanceResult.nearArea.length; i++)
			{
			if(!isNaN( parseFloat( distanceResult.nearArea[i].distance ) ))
				myDist = "(Entfernung: "+Math.round(distanceResult.nearArea[i].distance/0.00734)+"km)";

			erg += '<br />Zur <a href="./Kfz-Zulassungsstelle/'+distanceResult.nearArea[i].areaName+'/'+distanceResult.nearArea[i].k+'">'+distanceResult.nearArea[i].elementTitle+'</a>&nbsp;'+myDist+'&nbsp; ';
			}
			erg += "</p>";

		}

		erg += "</div>";
		$('auskunft_suchErgebnis').update(erg);
		$('auskunft_suchErgebnis').appear();
	}


	/*
	* helpers
	*/


/* mouse event handlers to uid1 */

function uid1_vcardClick(elem,id)
{    //pauseRotation(4000);
	//branchDetail(id);
	//if(PlzList_currentHightlight!=null)
	//{
	//  $(PlzList_currentHightlight).removeClassName("PlzList_active");
//	}
//	PlzList_currentHightlight = elem;
//	$(elem).addClassName("PlzList_active");

}

var isMouseOver = false;
function uid1_vcardOver(elem,id)
{
	if(!isMouseOver)
	{	isMouseOver = true;
	//  alert("pausing due to mover: "+isMouseOver);

 //  if(debugMode)
   	//console.info("over!");
	//	pauseRotation(4000);
	}
	//branchDetail(id);
	//$(elem).addClassName("PlzList_active");
	//new Effect.Appear($('fid'+id+"_link"));
	//$('fid'+id+"_link").show();
}

function uid1_vcardOut(elem,id)
{  isMouseOver = false;
   //alert("out and rotating="+isRotating);

 //  if(debugMode)
  // 	console.info("out, continue rotation");
 // continueRotation();
 //$(elem).removeClassName("PlzList_active");
 // $('fid'+id+"_link").hide();

}


/* helpers */



function randomFromArray(arr)
{
	return  arr[ Math.floor( arr.length * Math.random()  )] ;
}


function array_shuffle()
{
  var t, random,i=0;
  for(i =0; i < this.length; i++){
    random = Math.floor(Math.random() * this.length);
    t = this[i];
    this[i] = this[random];
    this[random] =t;
  }
}
  Array.prototype.shuffle = array_shuffle;


 function readCookie(name) {
	var nameEQ = name + "=";
	var ca = document.cookie.split(';');
	for(var i=0;i < ca.length;i++) {
		var c = ca[i];
		while (c.charAt(0)==' ') c = c.substring(1,c.length);
		if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length,c.length);
	}
	return null;
}


function dd(str)
{ if(debugMode) console.info(str); }




var PlzList_currentHightlight = 0; // deprecated

// JSTOOLS 2

function details(id){
	fixedMarkers.each(function(s) {

		if(typeof(s.getUserData)=='function')
			if(s.getUserData() == "s_"+id || s.getUserData() == "p_"+id)
			{
				map.panTo(s.getPoint());
				//s.blink(true, 200);
				highlightMarker(s);
				//setTimeout("s.blink(false, 0);", 3000);
				var marker = map.getFirstMarker();
				while (marker != null)
				{
					marker.closeDetailWin();
					marker.hideTooltip();
					marker = map.getNextMarker();
				}
			}
	});
}

function clickInfoBox(id) {
	if ($('stva' + id).visible() == true) {
		hideInfoBox(id);
	}
	else {
		showInfoBox(id);
		details(id);
	}
}

function showInfoBox(id) {
	new Effect.SlideDown('stva'+id);
}

function showOnlyInfoBox(id) {
	for(var i=0;i<stvas.length; i++ ) {
		if (stvas[i][0] && (stvas[i][0] != id)) {
			$('stva'+stvas[i][0]).hide();
		}
	}
	if ($('stva' + id) && $('stva' + id).visible() == false) {
		new Effect.SlideDown('stva' + id);
	}
}

function hideInfoBox(id) {
	new Effect.SlideUp('stva'+id);
}

function hideAllInfoBoxes() {
	for(var i=0;i<stvas.length; i++ ) {
		$('stva'+stvas[i][0]).hide();
	 }
}

function hideAllWithTimeout() {
	//if(stvas.length > 1)
	 window.setTimeout("hideAllInfoBoxes()",900);
}


function mouseOverInfoBox(id){

}

 

/* new on 25 aug 09 biz */
/* 
 * shows an adv in the box
 */
function showFid(fid)
{
	dd("show "+fid+" !");
	if($('fid'+fid))
	{
		 
	$('result1').update(" ");
 	$('result1').update($('fid'+fid).innerHTML);

	return true;
	}
	else {
	  dd(fid+" non-existent");
	 return false;
	}
}

 
