


/**
 * Page class
 * 
  */

leo.page = {
	confirmLightBoxReturnValue: false,
	/**
	 * Array of colums 
	 * 
	 * @private
	 * @type array
	 */
	_columns: [], 
    
	/**
	 * Array of _settingsComboBoxes 
	 * 
	 * @private
	 * @type array
	 */
	_settingsComboBoxes: [], 
    
    _reclist: null,
	
	/**
	 * Lock the movement
	 * 
	 * @private
	 * @type boolean
	 */
	_locked: false,
	_settings: false,
	_ajax: null,
	/**
	 * Init 
	 * 
	 * @param int tid
	 * @return void
	 */
	init: function() {
		this._addDragAndDrop();
	},
	
	/**
	 * Move
	 * 
	 * @param object obj
	 */
	move: function(obj) {	
		if (false == this._locked) {
			this._locked = true;
			el  = obj.element;							
			url = '/page/page/move/id/' + this._getIds(el.id).id; 
		 	right = $(el).nextSiblings()[0];
		 	if (undefined != right) {
			 	rightId = this._getIds(right.id)['id'];
				if (rightId == 'pageReview') 
					right = right.nextSiblings()[0];
		 	}
			
		 	if (undefined == right) {
		 		parentId = this._getIds(el.parentNode.id)['id'];
		 		url += '/parent/' + parentId;
			} else {
				rightId = this._getIds(right.id)['id'];
				url += '/right/' + rightId;
			}
			
			$(document.body).startWaiting('bigWaiting');
			this._ajax = new Ajax.Request(
				url,
				{
					method: 'post',
					onSuccess: function (transport) {
	 					// data = transport.responseText;
						// new Insertion.Top($(document.body), data);						
					},
					onComplete: function () {
						$(document.body).stopWaiting();
						this._locked = false;
					}.bind(this)
				}
			);
		}
	},
	
	/**
	 * Get id object from Element id
	 * 
	 * @param string id
	 * @private
	 * @return object
	 */
    _getIds: function(id) {			
		ids = id.split('_');
		return {module: ids[0], controller: ids[1], action: ids[2],	id: ids[3]};		
	},
	
	/**
	 * Get the id
	 * 
	 * @param string id
	 * @return string
	 */
	_getId: function(id) {
		return (id == undefined) ? '' : this._getIds(id)['id'];
	},
	
	/**
	 * Get module and controller
	 * 
	 * @param string id
 	 * @private
	 * @return string
	 */
	_getMC: function(id) {
		ids = _getIds(id);
		return ids['module'] + '_' + ids['controller'];
	},
	
	/**
	 * Get module, controller and action
	 * 
	 * @param string id
	 * @private
	 * @return string
	 */
	_getMCA: function(id) {
		ids = this._getIds(id);
		return ids['module'] + '_' + ids['controller'] + '_' + ids['action'];
	},	

	/**
 	 * Page make sortable
 	 * 
	 * @return void
	 */
	_makeSortable: function() 
	{
		this._destroyDragAndDrop();	
		this._getColumns().each(
			function (id) {
				Sortable.create(
					id, 
					{
						dropOnEmpty: true, 
						containment: this._getColumns(), 
						constraint: false,
						handle: 'handle', 
						hoverclass: 'edithoover',
						onUpdate: function() { 
							this.move(Draggables.activeDraggable);
						}.bind(this)
					}
				);
			}.bind(this)
		);
	},
	
	/**
	 * Is a drag and drop colum 
	 * 
	 * @param {Object} id
	 * @return boolean
	 */
	_isDragAndDropColumn: function(id)
	{
		return ('page_page_box' == this._getMCA(id)) ? true : false;
	},
	
	/**
	 * Get columns
	 * 
	 * @return array
	 */
	_getColumns: function(obj) {		
		if (this._columns.length == 0) {			
			$$('ul').each(
				function (el){										
					if (this._isDragAndDropColumn(el.id)) {
						this._columns.push(el.id);
					}
				}.bind(this)
			);
		}		
		return this._columns;
	},
	
	/**
	 * Page add drag and drop
	 * 
	 * @return void
	 */
	_addDragAndDrop: function() {		
		this._getColumns().each(
			function (column) {				
				this._makeSortable(column);				
			}.bind(this)
		);
	},
	
	/**
	 * Destroy drag and drop
	 * 
	 * @return void
	 */
	_destroyDragAndDrop: function() {
		this._getColumns().each(
			function (id) {
				Sortable.destroy(id);
			}
		);	
	},
	
	/**
	 * New page box
	 * 
	 * @param object el
	 * @return void
	 */
	boxNew: function(el, titleT) {
		// show lightbox with type selection
		myLightWindow.activateWindow(
			{
				href: el.href,
                title: titleT,
                width: lightWindowWidth3,
                height: lightWindowHeight,
				type: 'page',
				form: 'form_page_box_new'
			}				
		);
	},

	/**
	 * Send message
	 * 
	 * @param object el
	 * @return void
	 */
	 
	prepareComposeLightWindow: function() {
	   
        //$j(document).ready (function() {
           // 
        //});
        //$j('textarea.expanding').autogrow();
        /* Own */

        /* TextboxList */
        //document.observe('dom:loaded', function() {
           // tlist2 = new FacebookList('message_recipients', 'facebook-auto', {fetchFile:'/community/community/autocomplete'});
        //});
	    //alert(1);
	},
	 
	composeMessage: function(el) {
		// show lightbox with type selection
		myLightWindow.activateWindow(
			{
                href: el.href,
                width: lightWindowWidth6,
                height: 600,
                type: 'page',
                onLoaded: function () 
                            { 
                                if($('message_recipients')) 
                                    leo.page._reclist = new FacebookList('message_recipients', 'facebook-auto', {fetchFile:'/personal/community/autocomplete'});
                                $j('textarea.expanding').autogrow();
                            }
			}				
		);
	},

	replyMessage: function(el, titleT) {
		// show lightbox with type selection
		myLightWindow.activateWindow(
			{
				href: el.href,
                title: titleT,
                title: "Composer",
                width: lightWindowWidth6,
                /*height: 290,*/
                height: 600,
				type: 'page',
                onLoaded: function () 
                            { 
                                $j('textarea.expanding').autogrow();
                            }

			}				
		);
	},

	/**
	 * request connection
	 * 
	 * @param object el
	 * @return void
	 */
	requestConnection: function(el, titleT) {
		// show lightbox with type selection
		myLightWindow.activateWindow(
			{
                href: el.href,
                title: titleT,
                width: lightWindowWidth6, // much less displays an unwanted scrollbar in Safari/IE
                height: 600, // same with the height
                type: 'page',
                withJavascript: true
			}				
		);
	},
    
	/**
	 * message lightwindow
	 * 
     
                 onLoaded : null,
            onClosed : null
     
     
	 * @param object el
	 * @return void
	 */
	confirmLightwindow: function(message,returnFunction) {
		// show lightbox with type selection
        messageLightwindowMessage = message;
        leo.page.confirmLightBoxReturnValue = false;
		myLightWindow.activateWindow(
			{
				href: '/core/siteinfo/confirm',
                width: lightWindowWidth3, // much less displays an unwanted scrollbar in Safari/IE
                height: 300,
				type: 'page',
                onLoaded: leo.page.messageLightwindowChangeText,
                onClosed: returnFunction
			}				
		);
	},
    
	messageLightwindow: function(message) {
		// show lightbox with type selection
        messageLightwindowMessage = message;
		myLightWindow.activateWindow(
			{
				href: '/core/siteinfo/message',
                width: lightWindowWidth3, // much less displays an unwanted scrollbar in Safari/IE
                height: 300,
				type: 'page',
                onLoaded: leo.page.messageLightwindowChangeText
			}				
		);
	},
    
    messageLightwindowChangeText: function(message) {
        //alert(messageLightwindowMessage);
        $('messageLightwindowText').innerHTML = messageLightwindowMessage;
    },
    
    showHelpVideo: function(el) {
		// show lightbox with type selection
		myLightWindow.activateWindow(
			{
                href: el.href,
                width: 600,
                height: 400,
                type: 'page'
			}				
		);      
    },

	reloadCaptcha: function(link, image) {				
		this._ajax = new Ajax.Request("/core/register/reloadcaptcha", {
			method: 'post',
			onSuccess: function(transport, json) {
				image.src = '/captcha/' + json.captchaImage + '.png';
			}.bind(this),
			onComplete: function() {				
				
			}.bind(this)
		});
	},
	
	
	sendMessage: function(form, do_reload) {				
		this._ajax = new Ajax.Request(form.action, {
			method: form.method,
			parameters: {content: Object.toJSON($(form.getAttributeNode('id').nodeValue).serialize(true))},
			onSuccess: function(transport, json) {

			}.bind(this),
			onComplete: function() {				
				myLightWindow.deactivate();
				if (do_reload) {
					location.reload();
				}
			}.bind(this)
		});
	},

	
	/**
	 * Toggle box settings
	 * 
	 * @param {Object} link
	 * @return {void}
	 */
	toggleSettings: function (link) {
		el = $('page_page_box_' + link.href.split('/').pop() + '_settings');
		if (false === this._settings[el] || this._settings[el] === undefined) {
			this._ajax = new Ajax.Request(
				link.href, {
					method: 'post',
					onSuccess: function(transport) {
						el.innerHTML = transport.responseText;
					},
					onComplete: function () { 
                        if($('settingsOrderedList' + link.href.split('/').pop() + 'Select'))
                        {
                            //leo.page._settingsComboBoxes['settingsOrderedList' + link.href.split('/').pop() + 'Select_combo'] = ''; 
                            //alert("hallo1.3");
                            var tmp = new Autocompleter.ComboBox('settingsOrderedList' + link.href.split('/').pop() + 'Select');
                            //alert("hallo2");
                            leo.page._settingsComboBoxes['settingsOrderedList' + link.href.split('/').pop() + 'Select_combo'] = tmp; 
                            //alert("hallo3");
                        }
                        this._toggleSettings(el);
					}.bind(this)
				}
			);
		} else {
			this._toggleSettings(el);
		}
	},
	
	_toggleSettings: function (el)
	{
		new Effect.toggle(el.id, 'blind', {duration: 0.5});		
		this._settings[el] = !this._settings[el];
	},
	
	saveSettings: function (form)	
	{	
		this._ajax = new Ajax.Request(
			form.action, 
			{
				method: form.method,
				parameters: {content: Object.toJSON($(form.getAttributeNode('id').nodeValue).serialize(true))},
				onSuccess: function(transport, json) {
					//alert(transport.responseText);
				}.bind(this),
				onComplete: function() {									
					this._toggleSettings($('page_page_box_' + form.box_id.value + '_settings'));
					// this._boxReload($('page_page_box_' + form.box_id.value));
					window.location.reload();
				}.bind(this)
			}
		);
	},
	
	/**
	 * Add new page box
	 * 
	 * @param object el
	 * @param string type
	 * @return void
	 * @todo ajax response for box content and id
	 */
	boxAdd: function(form) {		
        var c0 = $$('.column0 .box-li').length;
        var c1 = $$('.column1 .box-li').length;
        var c2 = $$('.column2 .box-li').length;
        
        var m = Math.min(c0,c1,c2);
        var col = 0;
        if(m == c2)
            col = 2;
        if(m == c1)
            col = 1;
            
        $('insertIntoCol').value = col;
        
		this._ajax = new Ajax.Request(form.action, {
			method: form.method,
			parameters: {content: Object.toJSON($(form.getAttributeNode('id').nodeValue).serialize(true))},
			onSuccess: function(transport, json) {
				box = transport.responseText;

                    
				column = this._getColumns()[col];

				if (undefined != column) {
					new Insertion.Bottom(column, box);
				}
				this._makeSortable();	
			}.bind(this),
			onComplete: function() {				
				myLightWindow.deactivate();
			}.bind(this)
		});
	},
	
	/**
	 * Delete Box
	 * 
	 * @param object link
	 * @param int treeId
	 * @return void
	 */
	boxDelete: function(link, treeId) {
		if (false == this._locked) {
			this._locked = true;
			$(document.body).startWaiting('bigWaiting');
			this._ajax = new Ajax.Request(
				link.href,
				{
					method: 'post',
					onSuccess: function (transport) {	 											
					},
					onComplete: function () {
						$('page_page_box_' + treeId).remove();
						$(document.body).stopWaiting();
						this._makeSortable;
						this._locked = false;
					}.bind(this)
				}
			);
		}
	},
	
	_boxReload: function (el) {		
		// need the element, but is has the box id
		// el.innerHTML = 'Will be updated soon <br>' + el.innerHTML
	},
	
	getGalleryImageSelect: function (boxId, select) {
		settings = $('page_page_box_' + boxId + '_settings');
		settings_image = $('page_page_box_' + boxId + '_settings_image');		
		form = $('page_page_box_' + boxId + '_settings_form');
		url = '/gallery/settings/image/id/' + boxId + '/category/' + select.value;
		this._ajax = new Ajax.Request(
			url, {
				method: form.method,
				onSuccess: function(transport) {																					
					settings_image.innerHTML = transport.responseText;
				},
				onComplete: function () {					
//					this._toggleSettings(settings);
				}.bind(this)
			}
		);
	},
    
    
    /**
	 * Login
	 * 
	 * @param {Object} form
	 * @public
	 * @return {void}
	 */
	login: function(form, href)
	{
        if(form=='')
        {
            action = href;
            contentT = ' ';
        }
        else
        {
            action = form.action;
            contentT = Object.toJSON($(form.getAttributeNode('id').nodeValue).serialize(true));
        }
        //alert(contentT);
		this._ajax = new Ajax.Request(
			action, {
				method: 'post',
				parameters: {content: contentT},
				onSuccess: function(transport, json) {
                    //alert(transport.getAllHeaders());
					if (json.reload) {
                        window.location.href=json.reload
                        return;
                    } else {
                        if (json.LW) {
                            myLightWindow.activateWindow(
                                {
                                    href: json.LWhref,
                                    title: json.LWtitle,
                                    width: lightWindowWidth4,
                                    height: lightWindowHeight,
                                    type: 'page'
                                }				
                            );
                        }
                        
                        if (json.MB) {
                            myLightWindow.deactivate();
                            leo.page.messageLightwindow(json.MBmessage);
                        }
                        
                        if (json.message) {
                            //alert(form.id + '_message = ' + json.message); 
                            $(form.id + '_message').innerHTML = json.message;
                        }
                    }
                        
                }
            }
			
		);
	},
	/**
	 * Open the conact us formular in a lightbox
	 */
	openContactUs : function() {
		myLightWindow.activateWindow( 
        {
			href : '/core/contact/contact',
			width : lightWindowWidth6,
			height: 550,
			type: 'page',
			withJavascript: true
		});
	},

	/**
	 * display a light window
	 */
	disp_LW : function(lwhref, title) {
		myLightWindow.activateWindow(
		        {
		            href: lwhref,
		            title: title,
		            width: lightWindowWidth4,
		            height: lightWindowHeight,
		            type: 'page'
		        });
	},
	
	/**
	 * Page review
	 * 
	 * @param object link
	 * @return void
	 */
	reviewPage: function(linkUrl) {
		
		if (false == this._locked) {
			this._locked = true;
			this._ajax = new Ajax.Request(
				linkUrl,
				{
					method: 'post',
					onSuccess: function (transport) {	 											
					},
					onComplete: function () {
						parent.myLightWindow.deactivate();
						parent.document.getElementById('page_page_box_pageReview').remove();
						this._locked = false;
					}.bind(this)
				}
			);
		}
	},
	/**
	 * Delete profile
	 * 
	 * @param object link
	 * @return void
	 */
	deleteProfile: function(linkUrl) {
		
		if (false == this._locked) {
			this._locked = true;
			this._ajax = new Ajax.Request(
				linkUrl,
				{
					method: 'post',
					onSuccess: function (transport) {	
						window.location.href="/";
					},
					onComplete: function () {
						parent.myLightWindow.deactivate();
						this._locked = false;
					}.bind(this)
				}
			);
		}
	},
    /*
    openLightWindow: function(_href,_height,_width,more)
    {
        myLightWindow.activateWindow({href: hl,	width: 306, height: 300, type: 'page'});return false;
    
    },*/
	easy_call: function (actionHref) {
        this._ajax = new Ajax.Request(
            actionHref, {
                method: 'post',
                onSuccess: function(transport) {
                    return true;
                }.bind(this)
            }
        );
    },
	/**
	 * replaceElement
	 * 
	 * @param {String} element
	 * @param {String} actionHref
	 * @param {Boolean} aSynchron
	 * @return {void}
	 */
	replaceElement: function (element, actionHref) {
		replaceElement(element, actionHref, true);
	},
	replaceElement: function (element, actionHref, aSynchron) {
		el = $(element);
        this._ajax = new Ajax.Request(
            actionHref, {
            	asynchronous: aSynchron,
                method: 'post',
                onSuccess: function(transport) {
            	$(element).innerHTML = transport.responseText;
                }.bind(this)
            }
        );
	},
	replaceElementJS: function (element, actionHref, aSynchron) {
		el = $(element);
        this._ajax = new Ajax.Request(
            actionHref, {
            	asynchronous: aSynchron,
                method: 'post',
                onSuccess: function(transport) {
            	$(element).replace (transport.responseText);
                }.bind(this)
            }
        );
	},
	replaceEventCalendar: function (element, actionHref) {
		this._ajax = new Ajax.Request(
            actionHref, {
            	asynchronous: false,
                method: 'post',
                onSuccess: function(transport, json) {
            	var jsonX = transport.responseText.evalJSON();
                $('dateSelector').innerHTML = jsonX.dateSelector;
            	leo.form.innerHTML_js(jsonX.dateSelector, 'dateSelector');
            	$('events0').innerHTML = jsonX.event0;
            	$('events1').innerHTML = jsonX.event1;
            	$('events2').innerHTML = jsonX.event2;
            	$('events3').innerHTML = jsonX.event3;
            	$('currentTimestamp').value = jsonX.currentTimestamp;
            	}.bind(this)
            }
        );
	},
	fillCityCombobox: function (element, searchString, autoCompleter) {
        var countryId = $(element.id.replace('city', 'country').replace('_fake', '')).value;
		
        if (this._ajax != null)
      	    this._ajax.abort();
        
        this._ajax = new Ajax.Request(
            '/event/event/autocompletecities', {
            	asynchronous: true,
            	parameters: {search: searchString, country: countryId},
            	method: 'post',
                onSuccess: function(transport, json) {
            		autoCompleter.updateChoices(transport.responseText);
            	}.bind(this)
            }
        );
	},
	resetCityOnChange: function (element, autoCompleter) {
        var cityId = element.id.replace('country', 'city').replace('_fake', '');
	    $(cityId).value=''; 
    	$(cityId + '_fake').value='';
    },
    clearArtistFilter: function(form) {
      leo.page.replaceElementJS('genre_combos','/search/search/genreCombos/genre_id/0', false);
      form.reset();
      form.name.value="";
      form.ol_instrument_fake.value="";
      form.ol_language_fake.value="";
      form.ol_country_fake.value="";
      form.ol_atmosphere_fake.value="";
      form.ol_tempo_fake.value="";
      form.ol_free_mp3_fake.value="";
      leo.form.searchForm_submit(form);
    },
    clearMemberFilter: function(form) {
        form.reset();
        form.mname.value="";
        form.ol_ugroup_fake.value="";
        form.ol_country_fake.value="";
        leo.form.searchForm_submit(form);
      },
      clearLabelFilter: function(form) {
          leo.page.replaceElementJS('genre_combos','/search/search/genreCombos/genre_id/0', false);
          form.reset();
          form.lname.value="";
          form.ol_language_fake.value="";
          form.ol_country_fake.value="";
          leo.form.searchForm_submit(form);
        },
    clearEventCalendarFilter: function(form, date) {
    	this._ajax = new Ajax.Request(
        	'/event/calendar/clearfilter/date/' + date + '/column/0/strategy/1/search/', {
            	asynchronous: false,
                method: 'post',
                onSuccess: function(transport, json) {
        			form.reset();
        			var jsonX = transport.responseText.evalJSON();
                    $('dateSelector').innerHTML = jsonX.dateSelector;
                	leo.form.innerHTML_js(jsonX.dateSelector, 'dateSelector');
                	$('events0').innerHTML = jsonX.event0;
                	$('events1').innerHTML = jsonX.event1;
                	$('events2').innerHTML = jsonX.event2;
                	$('events3').innerHTML = jsonX.event3;
                	$('currentTimestamp').value = jsonX.currentTimestamp;
                }.bind(this)
            }
    	);
    },
    setEventCalendarFilter: function(form, date) {
    	
    	action = form.action;
        contentT = Object.toJSON($(form.getAttributeNode('id').nodeValue).serialize(true));
    	
    	this._ajax = new Ajax.Request(
    			action + 'date/' + date + '/column/0/strategy/1/search/', {
               	asynchronous: false,
                method: 'post',
                parameters: {content: contentT},
                onSuccess: function(transport, json) {
                	var jsonX = transport.responseText.evalJSON();
                    $('dateSelector').innerHTML = jsonX.dateSelector;
                	leo.form.innerHTML_js(jsonX.dateSelector, 'dateSelector');
                	$('events0').innerHTML = jsonX.event0;
                	$('events1').innerHTML = jsonX.event1;
                	$('events2').innerHTML = jsonX.event2;
                	$('events3').innerHTML = jsonX.event3;
                	$('currentTimestamp').value = jsonX.currentTimestamp;
                }.bind(this)
            }
    	);
    },
    afterUpdateProfileCityElement: function(field, selectedElement) {
    	if(!$(selectedElement))
            return;
        $('city_id').value = selectedElement.id;
      },
    onChangeProfileCountry: function() {
    	$('city').value = '';
    	$('city_id').value = -1;
      },
    fillRegisterCityCombobox: function (element, searchString, autoCompleter) {
        var countryId = $(element.id.replace('city', 'country').replace('_fake', '')).value;
		
        if (this._ajax != null)
      	    this._ajax.abort();
        
        this._ajax = new Ajax.Request(
            '/core/register/autocompletecities', {
            	asynchronous: true,
            	parameters: {search: searchString, country: countryId},
            	method: 'post',
                onSuccess: function(transport, json) {
            		autoCompleter.updateChoices(transport.responseText);
            	}.bind(this)
            }
        );
	},
	  printStatus: function(text) {
		  $('debug').value = text + "\n" + $('debug').value;
	  },
    fillEventCalendarCityCombobox: function (element, searchString, autoCompleter) {
		  var countryId = $(element.id.replace('city', 'country').replace('_fake', '')).value;
          
          if (this._ajax != null)
        	  this._ajax.abort();
        	  
          this._ajax = new Ajax.Request(
            '/event/calendar/autocompletecities', {
            	asynchronous: true,
            	parameters: {search: searchString, country: countryId},
            	method: 'post',
                onSuccess: function(transport, json) {
            		autoCompleter.updateChoices(transport.responseText);
            	}.bind(this)
            }
          );
	},
	fillEventCalendarStateCombobox: function (element, searchString, autoCompleter) {
        var countryId = $(element.id.replace('state', 'country').replace('_fake', '')).value;
		
        if (this._ajax != null)
      	    this._ajax.abort();
        
        this._ajax = new Ajax.Request(
            '/event/calendar/autocompletestates', {
            	asynchronous: true,
            	parameters: {search: searchString, country: countryId},
            	method: 'post',
                onSuccess: function(transport, json) {
            		autoCompleter.updateChoices(transport.responseText);
            	}.bind(this)
            }
        );
	}
}
