/*
 * Wadoptie.nl
 * Copyright(c) 2009, Maarten Baijs, Bart vd Hoek.
 * 
 * This code is licensed under BSD license. Use it as you wish, 
 * but keep this copyright intact.
 */

var wadoptieClass = new Class ({
	ideal: null,
	
	percelen: new Array(),
	
	text_stappen: {
		  stap1: ['<b>Stap 1 Kies op de kaart een wit vlak: hier wil ik een stuk wad adopteren!</b>', false]
		, stap2: ['<b>Stap 2 Kies op de kaart het perceel (een blauw blokje) dat je wilt adopteren.</b>', false]
		, stap3: ['<b>Stap 3 Vul je gegevens in</b>', false]
		, mijn_wad: ['Mijn stukje wad!', true]
	},
	
	setMapTitle: function(title_name) {
		var o = this.text_stappen[title_name];
		wadoptieObj.flashCall('setMapTitle', o[0], o[1]);
	},
	
	doAdopt: function(id, lat, lng) {
		var perceel = new Array();
		perceel['id']  = id;
		perceel['lat'] = lat;
		perceel['lng'] = lng;
		this.percelen.push(perceel);
		
		if ($('percelen_count')) {
			$('percelen_count').innerHTML = this.percelen.length;
		} else {
			var auto_select = '';
			if (document.forms['frm_register'])
				auto_select = '&adoptie_type=' + document.forms['frm_register']['adoptie_type'].value;
			
			ajxShowPage('index.php?c=adopt&a=select&count=' + this.percelen.length + auto_select);
		}
		
		wadoptieObj.setMapTitle('stap2');
	},
	
	undoAdopt: function(id) {
		var new_percelen = new Array();
		for(var x=0; x < this.percelen.length; x++) {
			if (this.percelen[x]['id'] != id)
				new_percelen.push(this.percelen[x]);
		}
		
		this.percelen = new_percelen;
		
		if ($('percelen_count')) {
			$('percelen_count').innerHTML = this.percelen.length;
		} else {
			var auto_select = '';
			if (document.forms['frm_register'])
				auto_select = '&adoptie_type=' + document.forms['frm_register']['adoptie_type'].value;

			ajxShowPage('index.php?c=adopt&a=select&count=' + this.percelen.length + auto_select);
		}
		
		wadoptieObj.setMapTitle('stap2');
	},
	resetAdopt: function() {
		this.percelen = new Array();
	},
	
	showMijnWad: function() { this.flashCall('showMijnWad'); },
	
	showProfileByWad: function(wad_id) {
		if (this.percelen.length > 0) {
			var c = confirm('Profiel bekijken?\nDit annuleert uw huidige selectie.');
			
			if (!c)
				return;
			
			this.flashCall('resetWadSelection');
		}

		ajxShowPage('index.php?c=adopt&a=show_profile&wad_id='+wad_id);
	},
	
	
	initialize: function()
	{
		oMap = $('flash_app');
	
		this.flashLoad();
	},
	
	
	setSifr: function(oSelector, color){
		var sColor = (color? color : '#003366');
		sIFR.replace(myriad, {
 			 selector: oSelector
  			,wmode: 'transparent'
  			,offsetTop: '7'
  			,css: '.sIFR-root { color: '+sColor+'}'
		});
	},
	
	loadIconPage: function (icon_id) {
		ajxShowPage('index.php?c=icon&a=view&icon_id=' + icon_id);
	},
	
	setEvents: function()
	{
		this.oBtnClose = $('close');
		this.oBtnToggle = $('toggle');
		this.oBtnDropdown = $('dropdown');
		this.oBtnSubmitform = $$('.submitform');
		this.oBtnGalleries = $$('.loadgallery');
		this.oBtnIdeal = $('btn-ideal');
		
		if(this.oBtnIdeal){
			this.oBtnIdeal.removeEvents('click');
			this.oBtnIdeal.addEvent('click', this.checkIdeal.bind(this));
		}		
		
		if(this.oBtnClose){
			this.oBtnClose.removeEvents('click');
			this.oBtnClose.addEvent('click', this.resizeMapWidth.bind(this));
		}
		
		if(this.oBtnToggle){
			this.oBtnToggle.removeEvents('click');
			$('bar').removeEvents('click');
			this.oBtnToggle.addEvent('click', this.resizeMapHeight.bind(this));
			$('bar').addEvent('click', this.resizeMapHeight.bind(this));
		}
		
		if(this.oBtnDropdown){
			this.oBtnDropdown.removeEvents('click');
			this.oBtnDropdown.addEvent('click', this.loadCategories.bind(this));
		}
			
		if(this.oBtnSubmitform){
			this.oBtnSubmitform.removeEvents();
			this.oBtnSubmitform.addEvent('click', this.submitForm.bind(this));
		}

		if(this.oBtnGalleries){
			this.oBtnGalleries.removeEvents();
			this.oBtnGalleries.addEvent('click', this.loadPanel.bind(this));
		}
		
		if(document){
			document.removeEvents('keydown');
			document.addEvent('keydown', function(oEvent){
		    	if (oEvent.control && oEvent.shift && oEvent.key == 'm' ){ this.oEaster = new Element('div', {'class': 'easter',
		    			'html': 'Gemaakt door: Bart, Maarten, Johnny, Marten, Rick, Arnold <embed src="swf/cat.mp3" /> ',
		    			'events': {'click': function(){this.destroy();}}
					}).inject($('wrapper'));
				}
			});	
		}
	},
	
	flashLoad: function()
	{
		var flash_vars = { };
		flash_vars['key'] = google_maps_key;
		flash_vars['mapTitle'] = this.text_stappen['stap1'][0];
		
		if (login_admin)
			flash_vars['login_admin'] = '1';
		else if (login_user)
			flash_vars['login_user'] = '1';
		
		flash_vars['wad_count'] = wad_ids.length;
		
		this.flMap = new Swiff('wadoptie.swf', {
    		id: 'googlemap'
		    ,width: '697px'
   			,height: '438px'
   			,params: { wMode: 'opaque' }
        	,vars: flash_vars
   			,container: oMap
		});
	},
	
	flashCall: function( Functie, Data )
	{
		var a = new Array();
		a.push(wadoptieObj.flMap.toElement());
		for(var x=0; x < arguments.length; x++) {
			a.push(arguments[x]);
		}
		
		Swiff.remote.apply(Swiff, a);
	},
	
	setTooltips: function()
	{
		var oTooltip = $$('.tooltip');
		var oTips = new Tips(oTooltip, {
		    className: 'tips'
		    ,offsets: {'x': 14, 'y': -40}
		});
	},

	getButton: function(oEvent)
	{
		var oBtn = $(oEvent.target);
		var oTag = oBtn.get('tag');
		
		if( oTag != 'a')
		{
			if( oTag != 'button'){
			oBtn = oBtn.getParent();
			}
		}
		return oBtn;
	},
		
	submitForm: function(oEvent)
	{
		oEvent.stop();
		var self = this;
		var oBtn = this.getButton(oEvent);
		var oForm = $(oBtn.get('rel'));
		var oParent = oForm.getParent();
		
		if(oForm){
			new Request.HTML ({
				url: sController,
				method: 'post',
				evalScripts:false,
            	evalResponse:false,
				onSuccess:function(responseTree, responseElements, responseHTML, responseJavaScript){
					if (oParent.hasClass('sub')) {
						oForm.getElement('.log').set('html', responseHTML).setStyle('display', 'block');
					}
					else {
						self.showBox(responseHTML);
					}
					$exec(responseJavaScript);
				 }
			}).post(oForm);
			
		}
	},
	
	
// -------------------------------------------------------------------------- //
// 'resize' functions
// -------------------------------------------------------------------------- //
	setMapState: function(){
		this.FX.state = false;
	},

	resizeMapWidth: function(oEvent)
	{	
		if(oEvent)oEvent.stop();

		if(!this.FX.state){
			this.FX.state = true;
			
			if( oBox.state ){
				this.FX.map.start('.mnarrow').chain(function(){
					oBox.self.setStyle('width', "400px");
					oBox.self.setStyle('margin', "10px 0 0 20px");
	    		});
			}
			else{
				oBox.self.setStyle('width', "0");
				oBox.self.setStyle('margin', "0");
				this.FX.map.start('.mwide');
			}
			oBox.state = !oBox.state;
			this.flashCall('toggleNavigationLeftRight', oBox.state);
			
		}
	},
	
	resizeMapHeight: function(oEvent)
	{
		if(oEvent)oEvent.stop();
		
		if(!this.FX.state){
			this.FX.state = true;

			this.FX.panel.start((oPanel.state? '.plarge' : '.psmall'));
			this.FX.map.start((oPanel.state? '.msmall' : '.mlarge'));
			this.FX.box.start((oPanel.state? '.bsmall' : '.blarge')).chain(function(){
        		oBox.scrollbar.update(true);
    		});
    		
    		if(!oPanel.state){
				oPanel.self.addClass("hide");
			}else{
				oPanel.self.removeClass("hide");
			}
			this.toggleSubpanel('hide');
			oPanel.state = !oPanel.state;
			this.flashCall('toggleNavigationUpDown', oPanel.state);
		}
	},
	
	toggleSubpanel: function(oCasename)
	{
		oPanel.self.getElements('.active').removeProperty('class');
		
		if( ( oCasename === 'hide' || oSub.self.hasClass(oCasename) ) ){
			oSub.self.removeProperty('class');
			return false;
		}
		else{
			oSub.self.removeProperty('class').addClass(oCasename);
			oSub.Btn.addClass('active');
			return true;
		}
	},
	
	loginAdmin: function(){
		if (!oAdmin.state){
			var fileJS = new Element('script', {
				'src': 'js/admin.js',
				'type': 'text/javascript',
				'class': 'asset_admin'
			});
			$$('head').adopt(fileJS);
			
			oAdmin.state = true;
			wadoptieObj.flashCall('loginAdmin', 'none');
		}
	},
		
	loginUser: function(){
		wadoptieObj.flashCall( 'loginUser', 'none' );
	},
	
	logoutAll: function(){
		if(oAdmin.state){
			oAdmin.self.logout();
			oAdmin.state = false;
		}
		wadoptieObj.flashCall( 'logoutAll', 'none' );
		var sFunction = 'logoutAll';
		var oRequest = new Request({method: 'post', url: sController});
		oRequest.send('function='+sFunction);
	},
	
// -------------------------------------------------------------------------- //
// load data functions
// -------------------------------------------------------------------------- //
	loadBox: function(aData)
	{
		var sFunction = aData[0], iId = aData[1];

		var oRequest = new Request({method: 'post', url: sController });
		oRequest.send('id='+iId+'&function='+sFunction);				
	},
	
	loadPanel: function(aData)
	{	
		if( $type(aData) === 'array' ){
			var iId = aData[1], sFunction = aData[0];
		}
		else if(aData == 'first'){
			var sFunction = 'getrandomgallery';
		}
		else{
			aData.stop();
			var iId = this.getButton(aData).get('rel');
			var sFunction = 'loadgallery-js';
		}
		
		var oRequest = new Request({method: 'post', url: sController });
		oRequest.send('id='+iId+'&function='+sFunction);	
	},
	
	loadCategories: function(oEvent)
	{
		var sFunction = 'loadcategories';
		
		oEvent.stop();
		oSub.Btn = oEvent.target;
		
		if(this.toggleSubpanel('categories')){	
			var oRequest = new Request({method: 'post', url: sController, onRequest: this.showLoader.create({arguments: 'sub', bind: this}), onSuccess: this.showCategories.bind(this)});
			oRequest.send('function='+sFunction);
		}	
	},
	
	loadRegister: function(aData)
	{
		var sFunction = aData[0], iId = aData[1], sLng = aData[2], sLat = aData[3];
	
		var oRequest = new Request({method: 'post', url: sController, onRequest: this.showLoader.create({arguments: 'box', bind: this}), onSuccess: this.showBox.bind(this)});
		oRequest.send('id='+iId+'&function='+sFunction+'&lng='+sLng+'&lat='+sLat);				
	},
	
	loadMRegister: function(iets)
	{
		var oRequest = new Request({method: 'post', url: sController, onRequest: this.showLoader.create({arguments: 'box', bind: this}), onSuccess: this.showBox.bind(this)});
		oRequest.send('function=test');				
	},
	
	checkIdeal: function(o)
	{
		this.ideal = this.statusIdeal.create({bind: this}).periodical(2000);
	},	
	
	statusIdeal: function()
	{
		var oRequest = new Request({method: 'post', url: sController, onComplete: this.returnIdeal.bind(this)});
		oRequest.send('function=getidealstatus');		
	},
	
	returnIdeal: function(status)
	{
		var self = this;
		if(status == 'success' ){
			$clear(this.ideal);
			
			new Request.HTML ({
			url: sController,
			method: 'post',
			evalScripts:false,
        	evalResponse:false,
			onSuccess:function(responseTree, responseElements, responseHTML, responseJavaScript){
					self.showBox(responseHTML);
					$exec(responseJavaScript);
			 }
			}).send('function=register-ideal');
			
		}
		
		else if( status == 'waiting' ){	
			

		}
		else{
			var oRequest3 = new Request({method: 'post', url: sController, onSuccess: this.showBox.bind(this)});
			oRequest3.send('function=fail-ideal');
			
		}
	},
	
// -------------------------------------------------------------------------- //
// show data functions
// -------------------------------------------------------------------------- //
	showBox: function( sHtml )
	{
		$$('.loader').destroy();
		if(sHtml){	
			oBox.viewport.set('html', sHtml);	
			if(oBox.state)this.resizeMapWidth();
			
			oBox.scrollbar.update();
			this.setSifr('#box h2');
			this.setEvents();
		}
	},
	
	showPanel: function( sHtml )
	{
		$$('.loader').destroy();
		if(sHtml){	
			$('images').set('html', sHtml);
			this.toggleSubpanel('hide');
			
			oGallery.update();
			
			if(oAdmin.state){oAdmin.self.createAdmin()}
			this.setEvents();
		}	
	},
	
	showCategories: function( sHtml )
	{	
		oSub.viewport.set('html', sHtml);
		oSub.scrollbar.update();	
		this.setEvents();
	}
});

wadoptieInit = function()
{
	wadoptieObj = new wadoptieClass();
	//oGallery = new galleryClass();
	//oBox.scrollbar = new scrollbarClass( oBox.viewport );
	//oSub.scrollbar = new scrollbarClass( oSub.viewport );
}

var wadoptieObj = {}, oMap = {}, oBox = {}, oPanel = {}, oSub = {}, oGallery = {}, oAdmin = {};
var sController = 'WadoptieController.php';

window.addEvent('domready', wadoptieInit);

