/*
      ##### #     ##                                       ##           /##   	
   ######  /#    #### /                  #              /####         #/ ###  	
  /#   /  / ##    ###/                  ###     #      /  ###        ##   ### 	
 /    /  /  ##    # #                    #     ##         /##        ##       	
     /  /    ##   #                            ##        /  ##       ##       	
    ## ##    ##   #    /###     /###   ###   ########    /  ##       ######   	
    ## ##     ##  #   / ###  / / ###  / ### ########    /    ##      #####    	
    ## ##     ##  #  /   ###/ /   ###/   ##    ##       /    ##      ##       	
    ## ##      ## # ##    ## ##    ##    ##    ##      /      ##     ##       	
    ## ##      ## # ##    ## ##    ##    ##    ##      /########     ##       	
    #  ##       ### ##    ## ##    ##    ##    ##     /        ##    ##       	
       /        ### ##    ## ##    ##    ##    ##     #        ##    ##       	
   /##/          ## ##    ## ##    ##    ##    ##    /####      ##   ##       	
  /  #####           ######   ######     ### / ##   /   ####    ## / ##       	
 /     ##             ####     ####       ##/   ## /     ##      #/   ##.nl    	
 #                                                 #                          	
  ##                                                ##                        	
*/


window.addEvent('domready', function() {
	

	
	//////////////////////////////////////////////////////////////////////// Initials
	////////////////////////////////////////////////////////////////////////
	
	var pos =0;
	
	user_request ? pos = user_request : pos = 91; 
	var old_menu;
	
	var content  = $('wrap_list');
	var menu     = $('wrap_menu');

	var mList = new Object();
	
	//////////////////////////////////////////////////////////////////////// practical functions
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////

	
	var fixText = function(text) {
		text = text.replace(/\r\n/g,'<br>');
		text = text.replace(/\n/g, 	'<br>');
		text = text.replace(/\r/g, 	'<br>');
		return text;
	}
	
	
	//////////////////////////////////////////////////////////////////////// Menu Items
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////


	var initMenu = function() {
	   	var request = new Request.JSON({
			url: 'lib/php/data.php?id=0' ,
			onRequest: function() {
				menu.empty();
			},
			onComplete: function(responseJSON) {
    			createMenuButtons(responseJSON);
   				openMenu(pos);
			}
		}).send();
    
	}
	
	initMenu();
	

	var createMenuButtons = function(results) {
	    
	    
        results.type.each(function(item, index) {
            var m       = new Element('div', {
	                    'class'	: 'menu_cell',
    	                'events': {
                        'click' : function() {
                            openMenu(results.id[index]);
                        },
                        'mouseover' : function() {
                        	if (index != 0) this.getElement('a').set('class','menu_button_over');
                        },
                        'mouseleave' : function() {
                        	if (results.id[index] != old_menu) {
	                            this.getElement('a').set('class','menu_button');
	                        }
                        }
                    } 
            }).inject(menu);
            
            						
            var m_link  = new Element('a', {
                'class'	: 'menu_button',
                'uid'	: results.id[index],
                'html'  : results.name[index] + ' '
            }).inject(m);
            if (index == 0) m.set('class','menu_cell_logo');
            
            if (results.id[index] == 1) {
				var spacer1  = new Element('div', {'class':'menu_cell'}).inject(menu);
				spacer1.setStyle('height','5px');
				spacer1.setStyle('width','100px');

            	results.submenu.type.each(function(item, index){
            		if (item == 'article') {
						var m       = new Element('div', {
									'class'	: 'menu_cell',
									'events': {
									'click' : function() {
										openMenu(results.submenu.id[index]);
									},
									'mouseover' : function() {
										this.getElement('a').set('class','menu_button_submenu_over');
									},
									'mouseleave' : function() {
										if (results.submenu.id[index] != old_menu) {
											this.getElement('a').set('class','menu_button_submenu');
										}
									}
								} 
						}).inject(menu);						
	
						var m_link  = new Element('a', {
							'class'	: 'menu_button_submenu',
							'uid'	: results.submenu.id[index],
							'html'  : results.submenu.name[index] + ' '
						}).inject(m);
					}
            	});
			            
				var spacer2  = new Element('div', {'class':'menu_cell'}).inject(menu);
				spacer2.setStyle('height','20px');
				spacer2.setStyle('width','100px');
	
            }
            if (!results.subcount[index]) {
            	m.hide();
            }
			if (results.id[index] == results.id.getLast()) {
            
				var m       = new Element('div', {'class'	: 'menu_cell'}).inject(menu);
				
										
				var m_link  = new Element('a', {
					'class'	: 'menu_email',
					'href'	: 'mailto:contact@desaga.com',
					'html'  : 'contact@desaga.com'
				}).inject(m);
			}
            
        });
        
    
    };
	
    openMenu = function(id) {
    	
		content.empty();
		
		pageTracker._trackPageview(id);
		
		if (old_menu) {
			var link = menu.getElement('a[uid=' + old_menu + ']');
			if (link) {
				if (link.get('class') == 'menu_button_submenu_over') link.set('class','menu_button_submenu'); 
				if (link.get('class') == 'menu_button_over') link.set('class','menu_button'); 
			}
		}
		old_menu = id;
		if (menu.getElement('a[uid=' + old_menu + ']')) {
			var cur_link = menu.getElement('a[uid=' + old_menu + ']');
			if (cur_link.get('class') == 'menu_button_submenu') cur_link.set('class','menu_button_submenu_over'); 
			if (cur_link.get('class') == 'menu_button') cur_link.set('class','menu_button_over'); 
		}

				
		
		var jsonRequest = new Request.JSON({
			url: "lib/php/data.php?id="+id, 
			link:'cantel',
			onSuccess: function (results, responseText) 
			{
				
				content.empty();
    			$$('body').setStyle('background-image','none');
			    // $('log').set('html',responseText);
				parseContent(results, id);
				
				
				
			}
		}).get();
		
		
        content.fade('in');
    };
    
    
	
	var parseContent = function(results, folder_id){
		
		
		if (results){
			results.type.each(function(item,index) {
				if (item == 'article') addArticle(results.id[index], results.name[index], index);
				if (item != 'article' || item != 'folder') 
				{
					create_item(
						content, 
						results.name[index], 
						results.id[index], 
						results.pos[index]-1,
						results.type[index],
						results.cont[index],
						folder_id
						);
				}	
				//$('log').set('html',responseText);										
			});
		}
	};
	
		
	//////////////////////////////////////////////////////////////////////// Create Items
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////


	
	
	
	var create_item = function(box, title, uid, pos, type, cont, folder_id) {
		var cell_end_height = 30;
		
		
		
		
		//////////////////////////////////////////////////////////////////////// Image
		////////////////////////////////////////////////////////////////////////
		
		if (type == 'img')
		{
			var cell_content	= new Element('div', {'class':'cell_img'}).inject(content);
			var img_x = 0;
			var img_y = 0;
			var json_req		= new Request.JSON({	url:'../../files/img/size.php?im='+title, 
														onSuccess:function(result,text){
															var size = 0;
															result.x > result.y ? size = result.x : size = result.y;
															if (size > 750) 
															{
																var ratio;
																var wanted = 750;
																if (result.x >= result.y) {
																	ratio = wanted / result.x;
																	img_y = ratio * result.y;
																	img_x = wanted;
																}
																if (result.y > result.x) {
																	ratio = wanted / result.y;
																	img_x = ratio * result.x;
																	img_y = result.y;
																}
																cell_content.setStyle('width',img_x);
																cell_content.setStyle('height',img_y);
																size = 750;
															} else {
																cell_content.setStyle('width',result.x);
																cell_content.setStyle('height',result.y);
															}
															
															cell_content.setStyle('background-image','url(../../files/img/pic.php?im='+title+'&size='+size+'&quality=90&x='+Math.floor(Math.random()*11) +')');
															
												
															
														}
													}).get();
			
		}

		//////////////////////////////////////////////////////////////////////// Gallery
		////////////////////////////////////////////////////////////////////////

		if (type == 'gallery')
		{
			var cell 			= new Element('div', {'class':'cell_gallery'}).inject(content);
			//cell.setStyle('overflow','hidden');
			
			var scroll = new Fx.Scroll(cell, {
				wait: false,
				duration: 800,
				offset: {'x': 0, 'y': 0},
				transition: Fx.Transitions.Quad.easeOut
			}).start();
			
			var cell_gallery_stroke				= new Element('div', {'html':' ','class':'cell_gallery_stroke'}).inject(cell);
			
			var cell_gallery 					= new Element('div', {'html':' ','class':'cell_gallery_page'}).inject(cell_gallery_stroke);
			var cell_gallery_main_navigation 	= new Element('div',{'class':'cell_gallery_navigation'}).inject(cell_gallery);
							
							
			var jsonRequest = new Request.JSON({
				url: "lib/php/data.php?id="+uid, 
				onSuccess: function (resp,text) 
				{
					if (resp) {
						
						var nav = new Element('div',{'class':'cell_gallery_navigation_button','html':'&#62;'}).inject(cell_gallery_main_navigation);
						nav.setStyle('margin-left','32px');
						nav.addEvent('click', function(e) {
							scroll.start(750,0);	
						});
						nav.addEvent('mouseover', function(e) {
							nav.highlight();
						});

						var nav_mass = new Element('div',{'class':'cell_gallery_navigation_text','html': resp.name.length}).inject(cell_gallery_main_navigation);
						nav_mass.setStyle('clear','none');
						nav_mass.setStyle('position','absolute');
						nav_mass.setStyle('left','100px');
						nav_mass.setStyle('top','35px');
						nav_mass.setStyle('font-family','courier');
						
						resp.name.each(function(item,index) {
							
							var thumb_size;
							resp.name.length >= 20 ? thumb_size = 100 : thumb_size = 120;
							var cell_gallery_img = new Element('img',{'class':'cell_gallery_img','src':'../../files/img/pic.php?im='+resp.name[index]+'&size='+thumb_size+'&quality=90&x='+Math.floor(Math.random()*11)}).inject(cell_gallery);
							
							cell_gallery_img.addEvent('click', function(e) {
								scroll.start((index*1 + 1) * 750,0);
							});
			
							
							var cell_gallery_page = new Element('div',{'class':'cell_gallery_page'}).inject(cell_gallery_stroke);
							cell_gallery_page.setStyle('height','450px');
							cell_gallery_page.setStyle('position','absolute');
							cell_gallery_page.setStyle('left',(index*1+1) * 750);



							
							// navigation

							var cell_gallery_navigation = new Element('div',{'class':'cell_gallery_navigation'}).inject(cell_gallery_page);




							// subtitle							

							var nav_text = new Element('div',{'class':'cell_gallery_navigation_text','html':resp.cont[index]}).inject(cell_gallery_navigation);
							
							
							// button left

							var nav_left = new Element('div',{'class':'cell_gallery_navigation_button','html':'&#60;'}).inject(cell_gallery_navigation);
							nav_left.setStyle('width',30);
							nav_left.addEvent('click', function(e) {
								scroll.start(index * 750,0);
							});
							nav_left.addEvent('mouseover', function(e) {
								nav_left.highlight();
							});


							// button right			

							var nav_right = new Element('div',{'class':'cell_gallery_navigation_button','html':'&#62;'}).inject(cell_gallery_navigation);
							nav_right.setStyle('left',0);
							nav_right.addEvent('click', function(e) {
								if (resp.id[parseInt(index) + 1])
								{
									scroll.start((index + 2) * 750,0);
								} else {
									scroll.start(0,0);
								}
							});
							nav_right.addEvent('mouseover', function(e) {
								nav_right.highlight();
							});


							// position

							var nav_pos = new Element('div',{'class':'cell_gallery_navigation_text','html': parseInt(index) + 1 + '/' + resp.name.length}).inject(cell_gallery_navigation);
							nav_pos.setStyle('clear','none');
							nav_pos.setStyle('position','absolute');
							nav_pos.setStyle('left','100px');
							nav_pos.setStyle('top','35px');
							nav_pos.setStyle('font-family','courier');
							
							
							// button home

							var nav_home = new Element('div',{'class':'cell_gallery_navigation_button_home'}).inject(cell_gallery_navigation);
							nav_home.setStyle('width',30);
							nav_home.setStyle('left','50px');
							nav_home.addEvent('click', function(e) {
								scroll.start(0);
							});
							nav_home.addEvent('mouseover', function(e) {
								//nav_home.highlight();
							});


							

							var cell_gallery_page_img = new Element('img',{'class':'cell_gallery_img','src':'../../files/img/pic.php?im='+resp.name[index]+'&size=430&restrict=x&quality=90&x='+Math.floor(Math.random()*11)}).inject(cell_gallery_page);
							cell_gallery_page_img.addEvent('click', function(e) {
								if (resp.id[parseInt(index) + 1])
								{
									scroll.start((index + 2) * 750,0);
								} else {
									scroll.start(0,0);
								}
								
							});
			
							
							
						});
					}
				}
			}).get();
			
		}
		
		//////////////////////////////////////////////////////////////////////// Date
		////////////////////////////////////////////////////////////////////////

		if (type == 'datefield')
		{
			var cell 			= new Element('div', {'class':'cell_item'}).inject(content);
			var cell_title 		= new Element('div', {'class':'cell_title'}).inject(cell);
			cell_title.load('lib/php/td.php?id='+folder_id);
			
			if (title != "") {
				var cell_date = new Element('div', {'html':title + ' ','class':'cell_title'}).inject(cell);
				cell_date.setStyle('color','black');
			}
		}

		//////////////////////////////////////////////////////////////////////// Textfield
		////////////////////////////////////////////////////////////////////////

		if (type == 'textfield')
		{

			var cell 			= new Element('div', {'class':'cell_item'}).inject(content);
			if (title != '')	var cell_title 		= new Element('div', {'html':title + ' ','class':'cell_title'}).inject(cell);
			var cell_textfield 	= new Element('div', {'html':fixText(cont) + ' ','class':'cell_textfield'}).inject(cell);
			cell.setStyle('width',600);
		}
		
		//////////////////////////////////////////////////////////////////////// Spacer
		////////////////////////////////////////////////////////////////////////

		if (type == 'img' || type == 'datefield' || type == 'gallery' || type == 'textfield' ) {
			var spacer 			= new Element('div', {'class':'cell_spacer'}).inject(content);
			if (type == 'datefield' && title == '') spacer.dissolve();
		}

		//////////////////////////////////////////////////////////////////////// Fx Background
		////////////////////////////////////////////////////////////////////////
		if (type == 'fx_background') {
			$$('body').setStyle('background-image','url(files/bg/'+title + ')');
		}
	}
	
	
	
	//////////////////////////////////////////////////////////////////////// Article
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	
	addArticle = function(id, title, index) {
		
		var cell 		= new Element('div').inject(content);
		var cell_top 	= new Element('div', {'class':'cell_item'}).inject(cell);
		var cell_bottom = new Element('div', {'class':'cell_item_bottom'}).inject(cell);
		var spacer 		= new Element('div', {'class':'cell_spacer'}).inject(cell);
		
		cell.setStyle('opacity',0.0);
		new Fx.Tween(cell, {
			property: 'opacity',
			link: 'chain',
			duration: 2000
		}).wait(200 * index).start(1.0);
		
		
		var jsonRequest = new Request.JSON({
			url: "lib/php/data.php?id="+id,
			link:'chain',
			onSuccess: function (responseJSON, responseText) 
			{
				
				//$('log').set('html',responseText);
				pushArticle(id,responseJSON,title, cell_top, cell_bottom);
//				alert(responseJSON);
				
			}
		}).get();
	};
	
	//////////////////////////////////////////////////////////////////////// Push Article
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	////////////////////////////////////////////////////////////////////////
	
	
	var pushArticle = function(id, list, title, cell_top, cell_bottom) {
		
		var cols = 2;
		var target_cell = cell_top;
		
		list.type.each(function(item, index){
			if (index <= 2) {

		//////////////////////////////////////////////////////////////////////// Image
		////////////////////////////////////////////////////////////////////////

				if (item == 'img') {
						var cell_content 	= new Element('div', {'class':'cell_img'}).inject(target_cell);
						
						var cell_fx_width 	= new Fx.Tween(cell_content, {	property: 'width',	link: 'cancel', duration: 600	}).start(1);
						var cell_fx_height 	= new Fx.Tween(cell_content, {	property: 'height',	link: 'cancel', duration: 3000 * (index*1+1)}).start(1);

						
						var img_x = 0;
						var img_y = 0;
						var json_req		= new Request.JSON({	url:'../../files/img/size.php?im='+list.name[index], 
																	onSuccess:function(result,text){
																		var size = 0;
																		result.x > result.y ? size = result.x : size = result.y;
																		if (size > 750) 
																		{
																			var ratio;
																			var wanted;
																			if (result.x >= result.y) {
																				wanted = 750;
																				ratio = wanted / result.x;
																				img_y = ratio * result.y;
																				img_x = wanted;
																			}
																			if (result.y > result.x) {
																				wanted = 550;
																				ratio = wanted / result.y;
																				img_x = ratio * result.x;
																				img_y = wanted;
																			}
																			size = 750;
																		} else {
																			img_x = result.x;
																			img_y = result.y;
																		}
																		
																		cell_content.setStyle('background-image','url(../../files/img/pic.php?im='+list.name[index]+'&size='+size+'&quality=90&x='+Math.floor(Math.random()*11) +')');
																		if ( result.x <= 380) {
																		
																			cell_bottom.inject(cell_top);
																			cell_bottom.setStyle('width','350px');
																			cell_fx_width.start(380);
																			//cell_content.setStyle('width','380px');
																		} else {
																			cell_fx_width.start(img_x);
																		}
																		cell_fx_height.start(img_y);
																
																		
																	}
																}).get();
															
						
				}
				
		//////////////////////////////////////////////////////////////////////// Gallery
		////////////////////////////////////////////////////////////////////////
				
				if (item == 'gallery') {

					var cell_content 	= new Element('div', {'class':'cell_img'}).inject(target_cell);
					
					var cell_fx_width 	= new Fx.Tween(cell_content, {	property: 'width',	link: 'cancel', duration: 600	}).start(1);
					var cell_fx_height 	= new Fx.Tween(cell_content, {	property: 'height',	link: 'cancel', duration: 3000 * (index*1+1)}).start(1);

					
					var img_x = 0;
					var img_y = 0;

					var jsonRequest = new Request.JSON({
						url: "lib/php/data.php?id="+list.id[index], 
						link:'chain',
						onSuccess: function (resp,text) 
						{
							if (resp) {
								var json_req		= new Request.JSON({	url:'../../files/img/size.php?im='+resp.name[0], 
																			onSuccess:function(result,text){
																				var size = 0;
																				result.x >= result.y ? size = result.x : size = result.y;
																				if (size > 750) 
																				{
																					var ratio;
																					var wanted;
																					if (result.x >= result.y) {
																						wanted = 750;
																						ratio = wanted / result.x;
																						img_y = ratio * result.y;
																						img_x = wanted;
																					}
																					if (result.x < result.y) {
																						wanted = 550;
																						ratio = wanted / result.y;
																						img_x = ratio * result.x;
																						img_y = wanted;
																						
																					}
																					size = wanted;
																				} else {
																					img_x = result.x;
																					img_y = result.y;
																				}
																				
																				cell_content.setStyle('background-image','url(../../files/img/pic.php?im='+resp.name[0]+'&size='+size+'&quality=90&x='+Math.floor(Math.random()*11) +')');
																				if ( img_x <= 380) {
																				
																					cell_bottom.inject(cell_top);
																					cell_bottom.setStyle('width',350);
																					cell_fx_width.start(380);
																					//cell_content.setStyle('width','380px');
																				} else {
																					cell_fx_width.start(img_x);
																				
																				}
																				cell_fx_height.start(img_y);
																			//	alert(img_y);

																			}
																		}).get();
							}
						}
					}).get();
					
	
				}
				
				target_cell = cell_bottom;
				
		//////////////////////////////////////////////////////////////////////// Title
		////////////////////////////////////////////////////////////////////////
				
				if (index == 0) {
					var cell_title 		= new Element('div', {'html':title + ' ','class':'cell_title'}).inject(target_cell);
				}

		//////////////////////////////////////////////////////////////////////// Date
		////////////////////////////////////////////////////////////////////////
				
				if (item == 'datefield') {
					//alert(list.name[index] + cols);
					if (list.name[index] != "") {
						var cell_date 		= new Element('div', {'html':list.name[index] + ' ','class':'cell_datefield'}).inject(target_cell);
					}
				}
				
		//////////////////////////////////////////////////////////////////////// Textfield
		////////////////////////////////////////////////////////////////////////

				if (item == 'textfield') {
					if (list.name[index]  != '' ) var cell_textfield_title	= new Element('div', {'html':list.name[index] + ' ','class':'cell_title'}).inject(target_cell);
					var longText = list.cont[index];
					if (longText.length > 500) {
						longText = longText.substr(0,500) + '...';
					}
					var cell_textfield 			= new Element('div', {'html':fixText(longText) + ' ','class':'cell_textfield'}).inject(target_cell);
				}
				
				
		//////////////////////////////////////////////////////////////////////// if no image 
				
				
				if (!cell_content) {
					cell_bottom.inject(cell_top);
				
				}
			}
			
		//////////////////////////////////////////////////////////////////////// More Button
		////////////////////////////////////////////////////////////////////////
			
			if (index == 3) {
				var more_button = new Element('a', {'html':'MEHR',	'class':'cell_button_more',
																	'events':{
																		'click':function(e) {
																			e.stop();
																			openMenu(id);
																		}
																	}
																	
																}).inject(target_cell);
				
			}		
			
				
			
			
		});
		
	};
	
	

	
	
});


