/**
 * @author nik
 */


var	myRequestURL				= "index.php?id=54&ce=326&JSonRequest=1";
var myDataRequest				= {'request' : '', 'toDo' : '', 'request_info' : {}};
var transfaireSyncMode			= false;
var durationSpeed 				= 500;



var isInternetExplorer = navigator.appName.indexOf("Microsoft") != -1;
// Verarbeiten aller FSCommand-Meldungen in einem Flash-Film
function plan_anim_DoFSCommand(command, args) {
	var plan_animObj = isInternetExplorer ? document.all.plan_anim : document.plan_anim;
	//
	// Geben Sie hier Ihren Code ein.
	//
	if(command=="hoverIN") {
	   highlightElements (args, true);
	//	alert(args);
	}
	if(command=="hoverOUT") {
	   highlightElements (args, false);
	 //   alert(args);
	}
}
// Hook fŸr Internet Explorer.
if (navigator.appName && navigator.appName.indexOf("Microsoft") != -1 && navigator.userAgent.indexOf("Windows") != -1 && navigator.userAgent.indexOf("Windows 3.1") == -1) {

/*
	document.write('<script language="VBScript" TYPE="text/vbscript" >\n');
	//document.write('MsgBox "Mirabile visu4."\n');
	document.write('On Error Resume Next\n');
	document.write('SUB plan_anim_FSCommand(ByVal command, ByVal args)\n');
	//document.write('	MsgBox "Mirabile visu5."\n');
	document.write('	Call plan_anim_DoFSCommand(command, args)\n');
	document.write('END SUB\n');
	document.write('</script\>\n');
*/

	document.write('<SCRIPT event=FSCommand(command,args) for=plan_anim>\n');
	document.write('	plan_anim_DoFSCommand(command, args);\n');
	document.write('</SCRIPT>\n');


}

window.addEvent('domready', function(){
	/*
	 * Debuging Help Output
	 */
	
	if ($('debugMe')) {
		myDebugMe = $('debugMe');
	} else {
		myDebugMe = false;
	}

	/*
	 * Bussy Icon
	 */

	if ($('bussy_icon')) {
		bussyIcon = $('bussy_icon');
	} else {
		bussyIcon = false;
	}

	/*
	 * nao_mapshower starter
	 */

	if ($('nao_mapshower')) {
		var nao_mapshower = $('nao_mapshower');
		animate_nao_mapshower (nao_mapshower);
	}

	/*
	 * Haustypen Navigation
	 */
	
	var haustypen_navigation_navlinks;
	var haustypen_navigation_mainNav;
	
	if ($('haustypen_navigation')) {
		
		/*
		 * Haustypen zu Navigation
		 */
		
		haustypen_navigation_navlinks = $$('div#haustypen_navigation li a');
		haustypen_navigation_navlinks.each(function(el){
			var myListElement = el.getParent('li');
			var myUID = myListElement.getProperty('forID');
			var myNavBrother = $(myUID);
			el.addEvent('mouseover', function() {
				highlightElements (myUID, true);
			});
			el.addEvent('mouseout', function() {
				highlightElements (myUID, false);
			}); 
		});
	}
	
	if ($('uid8')) {
		/*
		 * Navigation zu Haustypen
		 */

		var szNormal = 253, szSmall  = 132, szFull   = 495;
		 
		var kwicks = $$("#kwicks .BigNav_Element a");
		var fx = new Fx.Elements(kwicks, {wait: false, duration: 1000, transition: Fx.Transitions.Back.easeOut});
		kwicks.each(function(kwick, i) {
			kwick.addEvent("mouseenter", function(event) {
				var o = {};
				o[i] = {width: [kwick.getStyle("width").toInt(), szFull]}
				kwicks.each(function(other, j) {
					if(i != j) {
						var w = other.getStyle("width").toInt();
						if(w != szSmall) o[j] = {width: [w, szSmall]};
					}
				});
				fx.start(o);
			});
		});
		 
		$("kwicks").addEvent("mouseleave", function(event) {
			var o = {};
			kwicks.each(function(kwick, i) {
				o[i] = {width: [kwick.getStyle("width").toInt(), szNormal]}
			});
			fx.start(o);
		})
	}	

	haustypen_navigation_mainNav = $$('li#UID_22 a', 'li#UID_21 a', 'li#UID_20 a');
	haustypen_navigation_mainNav.each(function(el){
		var myListElement = el.getParent('li');
		var myUID = myListElement.getProperty('id');
		var myNavBrother = $("BIG_"+myUID);
		el.addEvent('mouseover', function() {
			//alert("test");
			highlightElements (myUID, true);
		});
		el.addEvent('mouseout', function() {
			//alert("test2");
			highlightElements (myUID, false);
		});
	});

	/*
	 * Immobilien Management
	 */

	if ($('add_new_log_entry')) {
		$('add_new_log_entry').addEvent('click', function(event){
			event.stop();
			if ($('new_immo_log_entry').get('value') != "") {
				myDataRequest['request'] 							= "insert_new_log";
				myDataRequest['toDo']								= "update_Log_Content";
				myDataRequest['request_info']['singleImo_Uid']		= $('add_new_log_entry').get('href');
				myDataRequest['request_info']['new_log_content']	= $('new_immo_log_entry').get('value');
				jsonRequest.post(transformRequestArrayToJSON(myDataRequest));
			}
		});
	}
// edit_immo_button save_button
	if ($$('a.save_changed_Immo_button')) {
		
		$$('a.save_changed_Immo_button').each(function(el) {
			el.setStyle('color', 'red');
			el.addEvent('click', function(event){
				event.stop();
				myDataRequest['request'] 							= "update_immo_values";
				myDataRequest['toDo']								= "follow_link";
				myDataRequest['request_info']['follow_link']		= el.get('href');
				myDataRequest['request_info']['singleImo_Uid']		= document.$_GET['editImmo'];
				myDataRequest['request_info']['newValues']			= {};
				if ($('furnished')) 			{myDataRequest['request_info']['newValues']['furnished']				= $('furnished').value;}
				if ($('construction_phase'))	{myDataRequest['request_info']['newValues']['construction_phase']		= $('construction_phase').value;}
				if ($('contact')) 				{myDataRequest['request_info']['newValues']['contact']					= $('contact').value;}
				if ($('area_manager')) 			{myDataRequest['request_info']['newValues']['area_manager']				= $('area_manager').value;}

				if ($('reserved'))				{myDataRequest['request_info']['newValues']['reserved']					= $('reserved').value;}
				if ($('sold'))					{myDataRequest['request_info']['newValues']['sold']						= $('sold').value;}
				if ($('customer'))				{myDataRequest['request_info']['newValues']['customer']					= $('customer').value;}
				if ($('rental_request'))		{myDataRequest['request_info']['newValues']['rental_request']			= $('rental_request').value;}

				if ($('deposit_done'))			{myDataRequest['request_info']['newValues']['deposit_done']				= $('deposit_done').value;}
				if ($('deposit_received_on'))	{myDataRequest['request_info']['newValues']['deposit_received_on']		= $('deposit_received_on').value;}
				if ($('deposit_amount'))		{myDataRequest['request_info']['newValues']['deposit_amount']			= $('deposit_amount').value;}

				if ($('deposit_2_done'))		{myDataRequest['request_info']['newValues']['deposit_2_done']			= $('deposit_2_done').value;}
				if ($('deposit_2_received_on'))	{myDataRequest['request_info']['newValues']['deposit_2_received_on']	= $('deposit_2_received_on').value;}
				if ($('deposit_2_amount'))		{myDataRequest['request_info']['newValues']['deposit_2_amount']			= $('deposit_2_amount').value;}
				
				if ($('balance'))				{myDataRequest['request_info']['newValues']['balance']					= $('balance').value;}
				
				if (window.console !== undefined) {console.log(myDataRequest);}
				jsonRequest.post(transformRequestArrayToJSON(myDataRequest));
			});
		});
	}
	if ($(document.body).getElement('div.anim_box')) {
		animateWindowCloser ();
	}
});

function animate_nao_mapshower (nao_mapshower) {
	/*
	 * base vars
	 */
	var boxOpen 	= false;
	var duration	= 500;
	var activLevel 	= "erdgeschoss";

	/*
	 * get animated box
	 */
	var txnaomapshowerpi1 = nao_mapshower.getParent('div.tx-naomapshower-pi1');
	/*
	 * get Switch button
	 */
	var nao_mapshower_switch_button = nao_mapshower.getElementById('nao_mapshower_switch_button');
	/*
	 * get map Buttons
	 */
	var erdgeschoss_button			= nao_mapshower.getElementById('erdgeschoss');
	var obergeschoss_button			= nao_mapshower.getElementById('obergeschoss');
	/*
	 * get map-boxes
	 */
	var erdgeschoss_box				= nao_mapshower.getElementById('pic_one_box');
	var obergeschoss_box			= nao_mapshower.getElementById('pic_two_box');
	/*
	 * initialize map-boxes and buttons
	 */
	erdgeschoss_box.setStyle('opacity', 1);
	obergeschoss_box.setStyle('opacity', 0);
	erdgeschoss_button.addClass('active_level_button');
	
	/*
	 * animation with options of Box
	 */
	var nao_mapshower_Fx = new Fx.Morph	(txnaomapshowerpi1, {duration: duration, transition: Fx.Transitions.Back.easeIn});
	
	/*
	 * maps anim
	 */
	var erdgeschoss_box_Fx = new Fx.Morph	(erdgeschoss_box, {duration: duration, transition: Fx.Transitions.Back.easeIn});
	var obergeschoss_box_Fx = new Fx.Morph	(obergeschoss_box, {duration: duration, transition: Fx.Transitions.Back.easeIn});

	/*
	 * open & close box anim
	 */
	nao_mapshower_switch_button.addEvent('click', function(e) {
		e.stop();
		//alert("anim start");
		//txnaomapshowerpi1.setStyle('top', '0');
		if (boxOpen) {
			boxOpen = false;
			nao_mapshower_Fx.start({'top': [-200, -850]});
		} else {
			boxOpen = true;
			nao_mapshower_Fx.start({'top': [-850, -200]});
		}
	});
	
	erdgeschoss_box.addEvent('click', function(e) {
		e.stop();
		//alert("anim start");
		//txnaomapshowerpi1.setStyle('top', '0');
		if (boxOpen) {
			boxOpen = false;
			nao_mapshower_Fx.start({'top': [-200, -850]});
		} else {
			boxOpen = true;
			nao_mapshower_Fx.start({'top': [-850, -200]});
		}
	});
	obergeschoss_box.addEvent('click', function(e) {
		e.stop();
		//alert("anim start");
		//txnaomapshowerpi1.setStyle('top', '0');
		if (boxOpen) {
			boxOpen = false;
			nao_mapshower_Fx.start({'top': [-200, -850]});
		} else {
			boxOpen = true;
			nao_mapshower_Fx.start({'top': [-850, -200]});
		}
	});
	erdgeschoss_button.addEvent('click', function(e) {
		e.stop();
		//alert("anim start");
		if (activLevel == "obergeschoss") {
			obergeschoss_box_Fx.start({'opacity': [1, 0]}).chain(function(){
				erdgeschoss_box_Fx.start({'opacity': [0, 1]}).chain(function(){
					activLevel = "erdgeschoss";
					obergeschoss_button.removeClass('active_level_button');
					erdgeschoss_button.addClass('active_level_button');
				});
			});
		}
	});
	obergeschoss_button.addEvent('click', function(e) {
		e.stop();
		//alert("anim start");
		if (activLevel == "erdgeschoss") {
			erdgeschoss_box_Fx.start({'opacity': [1, 0]}).chain(function(){
				obergeschoss_box_Fx.start({'opacity': [0, 1]}).chain(function(){
					activLevel = "obergeschoss"
					obergeschoss_button.addClass('active_level_button');
					erdgeschoss_button.removeClass('active_level_button');
				});
			});
		}
	});
	
}

function animateWindowCloser () {
	var MyCloseAnimBoxes = $$('div.anim_box');
	MyCloseAnimBoxes.each(function(MyCloseAnim){
		var MyCloseButton			= MyCloseAnim.getElement('a.anim_box_anchor');
		//var MyCloseAnim				= el.getElement('div.closer_anim');
		var MyCloseAnimStatus		= false;
		var MyClosedHigh			= MyCloseAnim.getElement('div.anim_box_headline').getSize().y+20;
        var MyCloseAnimSize			= $('Immo_list_filter_inner').getSize().y+MyClosedHigh+10;
		/*
		 * Anfangszustand geschlossene Boxen
		 */

		MyCloseAnim.set('styles', {'height': MyClosedHigh});
		MyCloseButton.addClass('closed');
		MyCloseAnimStatus			= true;

        var myEffect_MyCloseAnim	= new Fx.Morph(MyCloseAnim, {
            duration: durationSpeed,
            transition: Fx.Transitions.Sine.easeIn
        });


		MyCloseButton.addEvent('click', function(event){
			event.stop();
			//alert("The element is "+MyCloseAnimSize.x+" pixels wide and "+MyCloseAnimSize.y+"pixels high.");
	        if (MyCloseAnimStatus) {
				myEffect_MyCloseAnim.start({
		            'height': MyCloseAnimSize
		        });
				MyCloseButton.removeClass('closed');
				MyCloseAnimStatus		= false;
			} else {
				myEffect_MyCloseAnim.start({
		            'height': MyClosedHigh
		        });
				MyCloseButton.addClass('closed');
				MyCloseAnimStatus		= true;
			}

		});
	});	
}

function highlightElements (myNavigationID, hoverStatus) {
	
	//alert(myNavigationID);
	
	/*
	 * hover Navigation Element
	 */
	if ($(myNavigationID)) {
		if (hoverStatus) {
			$(myNavigationID).addClass('mapHover');
		} else {
			$(myNavigationID).removeClass('mapHover');
		}
	}
	
	/*
	 * Hover Big Navigation
	 */
	if ($("BIG_"+myNavigationID)) {
		if (hoverStatus) {
			$("BIG_"+myNavigationID).addClass('mapHover');
		} else {
			$("BIG_"+myNavigationID).removeClass('mapHover');
		}
	}
	/*
	 * Mini Flash Anim
	 */
	if (window.document.plan_anim) {
//		alert("plan_anim");
		window.document.plan_anim.SetVariable("testValue", myNavigationID+"#"+hoverStatus);
	}

}

function update_Log_Content (logData) {
	//var newLog = str_replace ("\n", "<br />\n", logData.data);
	var newLog = logData.data;
	$('single_immo_log').set('html', newLog);
}

/*
 * Server Communication
 */

var jsonRequestOptions = {
	url: myRequestURL,
	urlEncoded: true,
	async: transfaireSyncMode,

	/*
	 * Request.Periodical
	 */

    initialDelay: 1000,
    delay: 5000,
    limit: 15000,
	
	onRequest: function(){
		if (bussyIcon.addClass) {
			bussyIcon.addClass('request_bussy');
		}
	},
	onComplete: function(jsonObj){
		if (bussyIcon.removeClass) {
			bussyIcon.removeClass('request_bussy');
		}
		//if (myDebugMe) {var_dump(jsonObj, myDebugMe, 3);}
		//alert(jsonObj['toDo']);
		
		var toDo = jsonObj['toDo'];
		if (toDo != "") {
			switch (toDo) { //follow_link
				case "update_Log_Content":
					if (myDebugMe) {var_dump(jsonObj, myDebugMe, 10);}
					if (window.console !== undefined) {console.log(jsonObj);}
					update_Log_Content(jsonObj['result']);
					break;
				case "follow_link":
					if (myDebugMe) {var_dump(jsonObj, myDebugMe, 10);}
					if (window.console !== undefined) {console.log(jsonObj);}
					window.open(jsonObj['result']['request_info']['follow_link'], "_self");
					//update_Log_Content(jsonObj['result']);
					break;
				/*
				 * debug and error Part 
				 */
				
				case "debugError":
					//alert("Debuggig!");
					if (myDebugMe) {var_dump(jsonObj['result'], myDebugMe, 10);}
					break;
				default:
					alert("Unknown Order: " + jsonObj['toDo']);
					if (myDebugMe) {var_dump(jsonObj['result'], myDebugMe, 10);}
					if (window.console !== undefined) {console.log(jsonObj['result']);}
			}
		} //endif - toDo
	}
}
var jsonRequest = new Request.JSON(jsonRequestOptions);



/*
 * var_dump
 */

function var_dump (variable, target, maxDeep) {
	target.set('html', "<pre></pre>");
	target.getElement('pre').set('text', varDump(variable, maxDeep));
}

function varDump(variable, maxDeep)
{
	var deep = 0;
	var maxDeep = maxDeep || 5;

	function fetch(object, parent)
	{
		var buffer = '';
		deep++;

		for (var i in object) {
			if (parent) {
				objectPath = parent + '.' + i;
			} else {
				objectPath = i;
			}

			buffer += objectPath + ' (' + typeof object[i] + ')';

			if (typeof object[i] == 'object') {
				buffer += "\n";
				if (deep < maxDeep) {
					buffer += fetch(object[i], objectPath);
				}
			} else if (typeof object[i] == 'function') {
				buffer += "\n";
			} else if (typeof object[i] == 'string') {
				buffer += ': "' + object[i] + "\"\n";
			} else {
				buffer += ': ' + object[i] + "\n";
			}
		}

		deep--;
		return buffer;
	}

	if (typeof variable == 'object') {
		return fetch(variable);
	}

	return '(' + typeof variable + '): ' + variable + "\n";
}
/*
 * trasform Requestion Array to the JSon String.
 */
var transformRequestArrayToJSON = function(MyRequest){
    var myJSON = JSON.encode(MyRequest);
    var json = {
        'data': myJSON
    };
    return json;
};

/*
 * Zahlen runden
 */
function runde(x, n) {
	if (n < 1 || n > 14) return false;
	var e = Math.pow(10, n);
	var k = (Math.round(x * e) / e).toString();
	if (k.indexOf('.') == -1) k += '.';
	k += e.toString().substring(1);
	return k.substring(0, k.indexOf('.') + n+1);
}
/*
 * Shift-Click shiftclick
 */

Element.Events.shiftclick = {
    base: 'click', //we set a base type
    condition: function(event){ //and a function to perform additional checks.
        return (event.shift == true); //this means the event is free to fire
    }
};

/*
 * Array count
 */
Array.prototype.count = function () {
	return this.length;
}

/*
 * str_replace
 */

function str_replace (search, replace, subject, count) {
    // Replaces all occurrences of search in haystack with replace  
    // 
    // version: 909.322
    // discuss at: http://phpjs.org/functions/str_replace
    // +   original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   improved by: Gabriel Paderni
    // +   improved by: Philip Peterson
    // +   improved by: Simon Willison (http://simonwillison.net)
    // +    revised by: Jonas Raoni Soares Silva (http://www.jsfromhell.com)
    // +   bugfixed by: Anton Ongson
    // +      input by: Onno Marsman
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    tweaked by: Onno Marsman
    // +      input by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +   input by: Oleg Eremeev
    // +   improved by: Brett Zamir (http://brett-zamir.me)
    // +   bugfixed by: Oleg Eremeev
    // %          note 1: The count parameter must be passed as a string in order
    // %          note 1:  to find a global variable in which the result will be given
    // *     example 1: str_replace(' ', '.', 'Kevin van Zonneveld');
    // *     returns 1: 'Kevin.van.Zonneveld'
    // *     example 2: str_replace(['{name}', 'l'], ['hello', 'm'], '{name}, lars');
    // *     returns 2: 'hemmo, mars'
    var i = 0, j = 0, temp = '', repl = '', sl = 0, fl = 0,
            f = [].concat(search),
            r = [].concat(replace),
            s = subject,
            ra = r instanceof Array, sa = s instanceof Array;
    s = [].concat(s);
    if (count) {
        this.window[count] = 0;
    }
 
    for (i=0, sl=s.length; i < sl; i++) {
        if (s[i] === '') {
            continue;
        }
        for (j=0, fl=f.length; j < fl; j++) {
            temp = s[i]+'';
            repl = ra ? (r[j] !== undefined ? r[j] : '') : r[0];
            s[i] = (temp).split(f[j]).join(repl);
            if (count && s[i] !== temp) {
                this.window[count] += (temp.length-s[i].length)/f[j].length;}
        }
    }
    return sa ? s : s[0];
}

/*
 * Get §_GET Variablen
 */

(function(){ // Import GET Vars
   document.$_GET = [];
   var urlHalves = String(document.location).split('?');
   if(urlHalves[1]){
      var urlVars = urlHalves[1].split('&');
      for(var i=0; i<=(urlVars.length); i++){
         if(urlVars[i]){
            var urlVarPair = urlVars[i].split('=');
			tempUrlVarValue = urlVarPair[1].split('#');
            document.$_GET[urlVarPair[0]] = tempUrlVarValue[0]; //urlVarPair[1];
            if ((tempUrlVarValue[1]) && (tempUrlVarValue[1] != "")) {document.anchor = tempUrlVarValue[1];}
         }
      }
   }
})();


