﻿var MenuMatic = new Class({
	Implements: Options,
	options: {
        id: 'nav',//the id of the main menu (ul or ol)
        subMenusContainerId:'subMenusContainer',//id of the container div that will be generated to hold the submenus 
		
		//subMenu behavior
		effect: 'slide & fade',// 'slide', 'fade', 'slide & fade', or  null
		duration: 600,//duration of the effect in milliseconds
		physics: Fx.Transitions.Pow.easeOut,//how the effect behaves
		hideDelay: 1000,//in milliseconds, how long you have after moving your mouse off of the submenus before they dissapear
		
		//layout
		stretchMainMenu:false,//stretch main menu btn widths to fit within the width {set in the css} of the parent UL or OL
		matchWidthMode:false,//initial submenus match their parent button's width
		orientation: 'horizontal',//horizontal or vertical
		direction:{	x: 'right',	y: 'down' },//for submenus ( relative to the parent button )left or right, up or down
		tweakInitial:{ x:0, y:0	},//if you need to tweak the placement of the initial submenus
		tweakSubsequent:{ x:0, y:0 },//if you need to tweak the placement of the subsequent submenus
		center: false,// will attempt to center main nav element
		
		//dynamic style
		opacity: 95,//of the submenus
		mmbFocusedClassName:null,//main menu button classname, used for morphing to focused state
		mmbClassName:null,//main menu button classname, used for morphing back to original state
		killDivider:null,	
		
		fixHasLayoutBug:false,	
		
		onHideAllSubMenusNow_begin: (function(){}),
		onHideAllSubMenusNow_complete: (function(){}),
		
		onInit_begin: (function(){}),
		onInit_complete: (function(){})		

    },
	
	hideAllMenusTimeout:null,
	allSubMenus:[],
	subMenuZindex:1,
	
	initialize: function(options){		
		//if(Browser.Engine.webkit419){return;}		
        this.setOptions(options);
		this.options.onInit_begin();
		if(this.options.opacity > 99){this.options.opacity = 99.9;}
		this.options.opacity = this.options.opacity /100;

		Element.implement({
		    getId: function(){
				//If this element does not have an id, give it a unique one
		        if(!this.id){ 
					var uniqueId = this.get('tag') + "-" + $time();
					while($(uniqueId)){
						//make sure it is absolutely unique
						uniqueId = this.get('tag') + "-" + $time();						
					}
					this.id = uniqueId;						
				}
			    return this.id;
		    }
		});
		
		//initialize directions
		this.options.direction.x = this.options.direction.x.toLowerCase();
		this.options.direction.y = this.options.direction.y.toLowerCase();
		if(this.options.direction.x === 'right'){
			this.options.direction.xInverse = 'left';
		}else if(this.options.direction.x === 'left'){
			this.options.direction.xInverse = 'right';
		}
		if(this.options.direction.y === 'up'){
			this.options.direction.yInverse = 'down';
		}else if(this.options.direction.y === 'down'){
			this.options.direction.yInverse = 'up';
		}
		
		var links = $(this.options.id).getElements('a');
		
		links.each(function(item,index){
			
			//store parent links & child menu info
			item.store('parentLinks', item.getParent().getParents('li').getFirst('a'));
			
			item.store('parentLinks',item.retrieve('parentLinks').erase(item.retrieve('parentLinks').getFirst()));
			item.store('childMenu',item.getNext('ul') || item.getNext('ol'));
			
			//determine submenu type
			theSubMenuType = 'subsequent';
			
			//console.log($(this.options.id).getElements('ul, ol'));
			//console.log(item.getParent(['body ul,ol']));
			
			//console.log($(item.getParent('ul') || item.getParent('ol') ));
			
			if( $(item.getParent('ul') || item.getParent('ol') ).id === this.options.id){theSubMenuType = 'initial';	}
			item.store('subMenuType',theSubMenuType );
			
			//add classes to parents
			if(theSubMenuType === 'initial' && $(item.getNext('ul') || item.getNext('ol') )){
				item.addClass('mainMenuParentBtn');
			}else if($(item.getNext('ul') || item.getNext('ol') )){
				item.addClass('subMenuParentBtn');
			}			
		}.bind(this));
		
		//rip the submenus apart into separate divs inside of subMenusContainer
		var subMenusContainer = new Element('div', { 'id': this.options.subMenusContainerId	}).inject( $(document.body) ,'bottom');
		$(this.options.id).getElements('ul, ol').each(function(item,index){	
			new Element('div',{'class': 'smOW'}).inject(subMenusContainer).grab(item);		
		}.bind(this));		
		
		//set tabindex to -1 so tabbing through links in page does not go through hidden links in submenus container, since arrow keys can be used to navigate through submenus
		subMenusContainer.getElements('a').set('tabindex','-1'); 
		
		links.each(function(item,index){
			//only apply to links with subMenus
			if (!item.retrieve('childMenu')) {return;}
			
			//update childMenu pointer to look at smOW DIVs
			item.store('childMenu', item.retrieve('childMenu').getParent('div'));
			
			//add to allSubMenus array
			this.allSubMenus.include(item.retrieve('childMenu'));			
			
			//store parentSubMenus
			item.store('parentSubMenus',item.retrieve('parentLinks').retrieve('childMenu'));

			//now create the MenuMaticSubMenu class instances 
			var aSubMenu = new MenuMaticSubMenu(this.options,this, item);

		}.bind(this));
			
		//attach event handlers to non-parent main menu buttons
		var nonParentBtns = $(this.options.id).getElements('a').filter(function(item, index){ return !item.retrieve('childMenu'); });
		nonParentBtns.each(function(item, index){
			item.addEvents({
				'mouseenter': function(e){					
					//e = new Event(e).stop();
					this.hideAllSubMenusNow();	
					if(this.options.mmbClassName && this.options.mmbFocusedClassName){
						$(item).retrieve('btnMorph', new Fx.Morph(item, { 'duration':(this.options.duration/2), transition:this.options.physics, link:'cancel'})).start(this.options.mmbFocusedClassName); 
					}								
				}.bind(this),
				
				'focus': function(e){
					//e = new Event(e).stop();
					this.hideAllSubMenusNow();	
					if(this.options.mmbClassName && this.options.mmbFocusedClassName){
						$(item).retrieve('btnMorph', new Fx.Morph(item, { 'duration':(this.options.duration/2), transition:this.options.physics, link:'cancel'})).start(this.options.mmbFocusedClassName); 
					}
				}.bind(this),
				
				'mouseleave':function(e){
					//e = new Event(e).stop();
					if (this.options.mmbClassName && this.options.mmbFocusedClassName) {						
						$(item).retrieve('btnMorph', new Fx.Morph(item, {	'duration': (this.options.duration * 5),transition: this.options.physics,link: 'cancel'	})).start(this.options.mmbClassName);
					}	
				}.bind(this),
				
				'blur':function(e){
					//e = new Event(e).stop();
					if (this.options.mmbClassName && this.options.mmbFocusedClassName) {						
						$(item).retrieve('btnMorph', new Fx.Morph(item, {	'duration': (this.options.duration * 5),transition: this.options.physics,link: 'cancel'	})).start(this.options.mmbClassName);
					}					
				}.bind(this),
				
				'keydown' : function(e){
				    var event = new Event(e);
					if (e.key === 'up' || e.key === 'down' || e.key === 'left' || e.key === 'right') {	e.stop();	}
					
					if( e.key === 'left' && this.options.orientation === 'horizontal' || 
						e.key === 'up' && this.options.orientation === 'vertical'){
						
						if(item.getParent('li').getPrevious('li')){
							item.getParent('li').getPrevious('li').getFirst('a').focus();
						}else{
							item.getParent('li').getParent().getLast('li').getFirst('a').focus();
						}
					}else if(e.key === 'right' && this.options.orientation === 'horizontal' || 
							 e.key === 'down' && this.options.orientation === 'vertical'){
						if(item.getParent('li').getNext('li')){
							item.getParent('li').getNext('li').getFirst('a').focus();
						}else{
							item.getParent('li').getParent().getFirst('li').getFirst('a').focus();
						}	
					}
				}.bind(this)
			});
		}, this);

		
		this.stretch();
		this.killDivider();
		this.center();
		this.fixHasLayoutBug();
		this.options.onInit_complete();		
    },
	
	fixHasLayoutBug:function(){
		if(Browser.Engine.trident && this.options.fixHasLayoutBug){
			$(this.options.id).getParents().setStyle('zoom',1);
			$(this.options.id).setStyle('zoom',1);
			$(this.options.id).getChildren().setStyle('zoom',1);
			$(this.options.subMenusContainerId).setStyle('zoom',1);
			$(this.options.subMenusContainerId).getChildren().setStyle('zoom',1);
		}		
	},
	
	center:function(){
		if(!this.options.center){return;}
		$(this.options.id).setStyles({'left':'50%','margin-left': -($(this.options.id).getSize().x/2) });
	},
	
	stretch:function(){
		//stretch main menu btn widths to fit within the width of the parent UL or OL
		if(this.options.stretchMainMenu  && this.options.orientation === 'horizontal'){
			var targetWidth = parseFloat($(this.options.id).getCoordinates().width) ;
			var totalBtnWidth = 0;
			var mainBtns = $(this.options.id).getElements('a');
			mainBtns.setStyles({'padding-left':0,'padding-right':0});
			mainBtns.each(function(item,index){ totalBtnWidth+= item.getSize().x; }.bind(this));
			if(targetWidth < totalBtnWidth){return;}
			var increment = (targetWidth - totalBtnWidth)/ mainBtns.length;
			mainBtns.each(function(item,index){ item.setStyle('width',item.getSize().x+increment);	}.bind(this));
			mainBtns.getLast().setStyle('width',mainBtns.getLast().getSize().x-1);
		}
	},
	
	killDivider:function(){
		if(this.options.killDivider && this.options.killDivider.toLowerCase() === 'first'){
			$($(this.options.id).getElements('li')[0]).setStyles({'background':'none'});
		}else if(this.options.killDivider && this.options.killDivider.toLowerCase() === 'last'){
			$($(this.options.id).getElements('li').getLast()).setStyles({'background':'none'});
		}
	},

	hideAllSubMenusNow: function(){
		this.options.onHideAllSubMenusNow_begin();
		$clear(this.hideAllMenusTimeout);
		$$(this.allSubMenus).fireEvent('hide');
		this.options.onHideAllSubMenusNow_complete();	
	} 
	
});

var MenuMaticSubMenu = new Class({
	Implements: Options,
	Extends: MenuMatic,
    options: {
		onSubMenuInit_begin: (function(subMenuClass){}),
		onSubMenuInit_complete: (function(subMenuClass){}),
		
		onMatchWidth_begin: (function(subMenuClass){}),
		onMatchWidth_complete: (function(subMenuClass){}),
		
		onHideSubMenu_begin: (function(subMenuClass){}),
		onHideSubMenu_complete: (function(subMenuClass){}),
		
		onHideOtherSubMenus_begin: (function(subMenuClass){}),
		onHideOtherSubMenus_complete: (function(subMenuClass){}),		
		
		onHideAllSubMenus_begin: (function(subMenuClass){}),
		onHideAllSubMenus_complete: (function(subMenuClass){}),
		
		onPositionSubMenu_begin: (function(subMenuClass){}),
		onPositionSubMenu_complete: (function(subMenuClass){}),
		
		onShowSubMenu_begin: (function(subMenuClass){}),
		onShowSubMenu_complete: (function(subMenuClass){})
	},
	root:null,
	btn:null,
	hidden:true,
	myEffect:null,
		
	initialize: function(options,root,btn){
		this.setOptions(options);		
		this.root = root;
		this.btn = btn;
		this.childMenu = this.btn.retrieve('childMenu');
		this.subMenuType = this.btn.retrieve('subMenuType');
		this.childMenu = this.btn.retrieve('childMenu');
		this.parentSubMenus =  $$(this.btn.retrieve('parentSubMenus'));
		this.parentLinks =  $$(this.btn.retrieve('parentLinks'));
		this.parentSubMenu = $(this.parentSubMenus[0]);
		if(this.parentSubMenu ){this.parentSubMenu =this.parentSubMenu.retrieve('class');}
		this.childMenu.store('class',this);
		this.btn.store('class',this);
		this.childMenu.store('status','closed')
		
		this.options.onSubMenuInit_begin(this);		
		
		//add hide Event
		this.childMenu.addEvent('hide',function(){this.hideSubMenu();}.bind(this));
		
		//add show Event
		this.childMenu.addEvent('show',function(){this.showSubMenu();}.bind(this));

		if(this.options.effect){
			this.myEffect = new Fx.Morph(
				$(this.childMenu).getFirst(), {	duration: this.options.duration, transition: this.options.physics,  link: 'cancel' } 
			);
		}
		if(this.options.effect === 'slide' || this.options.effect === 'slide & fade'){
			if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' ) {
				this.childMenu.getFirst().setStyle('margin-top','0' );
			}else {
				this.childMenu.getFirst().setStyle('margin-left', '0');
			}
			
		}else if (this.options.effect === 'fade' || this.options.effect === 'slide & fade'){
			this.childMenu.getFirst().setStyle('opacity',0 );
		}
		
		if (this.options.effect != 'fade' && this.options.effect != 'slide & fade') {
			this.childMenu.getFirst().setStyle('opacity',this.options.opacity);
		}

		
		//attach event handlers to non-parent sub menu buttons
		var nonParentBtns = $(this.childMenu).getElements('a').filter(function(item, index){ return !item.retrieve('childMenu'); });
		nonParentBtns.each(function(item, index){
			$(item).addClass('subMenuBtn');
			
			item.addEvents({
				'mouseenter': function(e){
					this.childMenu.fireEvent('show');
					this.cancellHideAllSubMenus();					
					this.hideOtherSubMenus();				
				}.bind(this),
				
				'focus': function(e){
					this.childMenu.fireEvent('show');
					this.cancellHideAllSubMenus();		
					this.hideOtherSubMenus();
				}.bind(this),
				
				'mouseleave': function(e){
					this.cancellHideAllSubMenus();
					this.hideAllSubMenus();					
				}.bind(this),
				
				'blur': function(e){
					this.cancellHideAllSubMenus();
					this.hideAllSubMenus();
				}.bind(this),
				
				'keydown' : function(e){
				    var event = new Event(e);
					
					if (e.key === 'up' || e.key === 'down' || e.key === 'left' || e.key === 'right' || e.key === 'tab') {	e.stop();	}
					
					if(e.key === 'up'){
						if(item.getParent('li').getPrevious('li')){
							//move focus to the next link up if possible
							item.getParent('li').getPrevious('li').getFirst('a').focus();
						}else if(this.options.direction.y ==='down'){
							//move focus to the parent link
							this.btn.focus();
						}else if(this.options.direction.y ==='up'){
							//move focus to the last link in the subMenu
							item.getParent('li').getParent().getLast('li').getFirst('a').focus();
						}
					}else if(e.key === 'down'){
						if(item.getParent('li').getNext('li')){
							//move focus to the next link down if possible
							item.getParent('li').getNext('li').getFirst('a').focus();
						}else if(this.options.direction.y ==='down'){
							//move focus to the first link in the submenu
							item.getParent('li').getParent().getFirst('li').getFirst('a').focus();
						}else if(this.options.direction.y ==='up'){
							//move focus to the parent link
							this.btn.focus();
						}
					}else if(e.key === this.options.direction.xInverse){
						this.btn.focus();
					}
				}.bind(this)
			});
			
		}, this);
		
		$(this.btn).removeClass('subMenuBtn');
		
		if (this.subMenuType == 'initial') {
			this.btn.addClass('mainParentBtn');	
		}else{	
			this.btn.addClass('subParentBtn');	
		}
		
		//attach event handlers to parent button
		$(this.btn).addEvents({
			'mouseenter' : function(e){
				//e = new Event(e).stop();
				this.cancellHideAllSubMenus();
				this.hideOtherSubMenus();
				this.showSubMenu();
				if(this.subMenuType === 'initial' && this.options.mmbClassName && this.options.mmbFocusedClassName){
					$(this.btn).retrieve('btnMorph', new Fx.Morph($(this.btn), { 'duration':(this.options.duration/2), transition:this.options.physics, link:'cancel' })).start(this.options.mmbFocusedClassName);
				}
			}.bind(this),
			
			'focus' : function(e){
				//e = new Event(e).stop();
				this.cancellHideAllSubMenus();
				this.hideOtherSubMenus();
				this.showSubMenu();
				if(this.subMenuType === 'initial' && this.options.mmbClassName && this.options.mmbFocusedClassName){
					$(this.btn).retrieve('btnMorph', new Fx.Morph($(this.btn), { 'duration':(this.options.duration/2), transition:this.options.physics, link:'cancel' })).start(this.options.mmbFocusedClassName);
				}
			}.bind(this),
				
			'mouseleave': function(e){
				//e = new Event(e).stop();
				this.cancellHideAllSubMenus();
				this.hideAllSubMenus();
			}.bind(this),
			
			'blur': function(e){
				//e = new Event(e).stop();
				this.cancellHideAllSubMenus();
				this.hideAllSubMenus();
			}.bind(this),
			
			'keydown' : function(e){
			    e = new Event(e)
				if (e.key === 'up' || e.key === 'down' || e.key === 'left' || e.key === 'right') {	e.stop();	}
				
				if(!this.parentSubMenu){
					//main menu parent buttons
					if(
						this.options.orientation === 'horizontal' && e.key === this.options.direction.y ||
						this.options.orientation === 'vertical' && e.key === this.options.direction.x
					){
						if(this.options.direction.y ==='down'){
							//move focus to the first link in the child menu
							this.childMenu.getFirst().getFirst('li').getFirst('a').focus();
						}else if(this.options.direction.y ==='up'){
							//move focus to the first link in the child menu
							this.childMenu.getFirst().getLast('li').getFirst('a').focus();
						}
					}else if(
						this.options.orientation === 'horizontal' && e.key === 'left' ||
						this.options.orientation === 'vertical' && e.key === this.options.direction.yInverse 
					){
						//move focus to the previous link if possible, if not, move focus to the last link in the menu
						if(this.btn.getParent().getPrevious()){
							this.btn.getParent().getPrevious().getFirst().focus();
						}else{
							this.btn.getParent().getParent().getLast().getFirst().focus();
						}
					}else if(
						this.options.orientation === 'horizontal' && e.key === 'right' ||
						this.options.orientation === 'vertical' && e.key === this.options.direction.y 
					){
						//move focus to the next link if possible, if not, move focus to the first link in the menu
						if (this.btn.getParent().getNext()) {
							this.btn.getParent().getNext().getFirst().focus();
						}else{
							this.btn.getParent().getParent().getFirst().getFirst().focus();
						}
					}
				}else{
					if(e.key === 'tab'){e.stop();}
					//submenu parent buttons
					if (e.key === 'up') {
						if (this.btn.getParent('li').getPrevious('li')) {
							//move focus to the next link up
							this.btn.getParent('li').getPrevious('li').getFirst('a').focus();
						}else if(this.options.direction.y === 'down'){
							//move focus to the parent link
							this.parentSubMenu.btn.focus();
						}else if(this.options.direction.y === 'up'){
							//move focus to the bottom link in this submenu
							this.btn.getParent('li').getParent().getLast('li').getFirst('a').focus();
						}
					}else if(e.key === 'down'){
						if(this.btn.getParent('li').getNext('li')){
							//move focus to the next link down
							this.btn.getParent('li').getNext('li').getFirst('a').focus();
						}else if(this.options.direction.y === 'down'){
							//move focus to the top link in this submenu
							this.btn.getParent('li').getParent().getFirst('li').getFirst('a').focus();
						}else if(this.options.direction.y === 'up'){
							//move focus to the parent link
							this.parentSubMenu.btn.focus();
						}
					}else if(e.key === this.options.direction.xInverse){
						this.parentSubMenu.btn.focus();
					}else if(e.key === this.options.direction.x){
						if(this.options.direction.y === 'down'){
							this.childMenu.getFirst().getFirst('li').getFirst('a').focus();
						}else if(this.options.direction.y === 'up'){
						//	this.childMenu.getFirst().getLast('li').getFirst('a').focus();
						}
					}
				}
			}.bind(this)	
		});
		
		this.options.onSubMenuInit_complete(this);
		
    },
	
	matchWidth:function(){
		if (this.widthMatched || !this.options.matchWidthMode || this.subMenuType === 'subsequent'){return;}
		this.options.onMatchWidth_begin(this);
		var parentWidth = this.btn.getCoordinates().width;
		$(this.childMenu).getElements('a').each(function(item,index){
			var borderWidth = parseFloat($(this.childMenu).getFirst().getStyle('border-left-width')) + parseFloat($(this.childMenu).getFirst().getStyle('border-right-width'));
			var paddingWidth = parseFloat(item.getStyle('padding-left')) +	 parseFloat(item.getStyle('padding-right'));
			var offset = borderWidth + paddingWidth ;
			if(parentWidth > item.getCoordinates().width){
				item.setStyle('width',parentWidth - offset);
				item.setStyle('margin-right',-borderWidth);
			}
		}.bind(this));
		this.width = this.childMenu.getFirst().getCoordinates().width;
		this.widthMatched = true;
		this.options.onMatchWidth_complete(this);
	},
	
	hideSubMenu: function() {	
		if(this.childMenu.retrieve('status') === 'closed'){return;}	
		this.options.onHideSubMenu_begin(this);
		if (this.subMenuType == 'initial') {
			if(this.options.mmbClassName && this.options.mmbFocusedClassName){
				$(this.btn).retrieve('btnMorph', new Fx.Morph($(this.btn), { 'duration':(this.options.duration), transition:this.options.physics, link:'cancel' })).start(this.options.mmbClassName )
				.chain(function(){
					$(this.btn).removeClass('mainMenuParentBtnFocused');
					$(this.btn).addClass('mainMenuParentBtn');
				}.bind(this));
			}else{
				$(this.btn).removeClass('mainMenuParentBtnFocused');
				$(this.btn).addClass('mainMenuParentBtn');
			}
		}else{
			$(this.btn).removeClass('subMenuParentBtnFocused');
			$(this.btn).addClass('subMenuParentBtn');
		}
		
		this.childMenu.setStyle('z-index',1);
		
		if(this.options.effect && this.options.effect.toLowerCase() === 'slide'){
			if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' && this.options.direction.y === 'down') {
				this.myEffect.start({ 'margin-top': -this.height }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' && this.options.direction.y === 'up') {
				this.myEffect.start({ 'margin-top': this.height }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if(this.options.direction.x === 'right'){
				this.myEffect.start({ 'margin-left': -this.width }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if(this.options.direction.x === 'left'){
				this.myEffect.start({ 'margin-left': this.width }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}
		}else if(this.options.effect == 'fade'){
			this.myEffect.start({ 'opacity': 0 }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
		}else if(this.options.effect == 'slide & fade'){
			
			if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' && this.options.direction.y === 'down') {
				this.myEffect.start({ 'margin-top': -this.height,opacity:0 }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' && this.options.direction.y === 'up') {
				this.myEffect.start({ 'margin-top': this.height,opacity:0 }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if(this.options.direction.x === 'right'){
				this.myEffect.start({ 'margin-left': -this.width,opacity:0 }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}else if(this.options.direction.x === 'left'){
				this.myEffect.start({ 'margin-left': this.width, opacity:0 }).chain(function(){	this.childMenu.style.display = "none";	}.bind(this));
			}
		}else{
			this.childMenu.style.display = "none";
		}
		this.childMenu.store('status','closed');
		this.options.onHideSubMenu_complete(this);
	},
	
	hideOtherSubMenus: function() {		
		this.options.onHideOtherSubMenus_begin(this);
		//set up otherSubMenus element collection
		if(!this.btn.retrieve('otherSubMenus')){
			this.btn.store('otherSubMenus', $$(this.root.allSubMenus.filter(function(item){ return !this.btn.retrieve('parentSubMenus').contains(item) && item != this.childMenu; }.bind(this)) ));
		}		
		this.parentSubMenus.fireEvent('show');
		this.btn.retrieve('otherSubMenus').fireEvent('hide');
		this.options.onHideOtherSubMenus_complete(this);
	},
	
	hideAllSubMenus: function(){
		this.options.onHideAllSubMenus_begin(this);
		$clear(this.root.hideAllMenusTimeout);
		this.root.hideAllMenusTimeout = (function(){
			$clear(this.hideAllMenusTimeout);			
			$$(this.root.allSubMenus).fireEvent('hide');			
		}).bind(this).delay(this.options.hideDelay);
		this.options.onHideAllSubMenus_complete(this);		
	},

	cancellHideAllSubMenus: function(){ 
		$clear(this.root.hideAllMenusTimeout);	
	},
	
	showSubMenu: function(now){		
		if(this.childMenu.retrieve('status') === 'open'){return;}
		this.options.onShowSubMenu_begin(this);
		if (this.subMenuType == 'initial') {
			$(this.btn).removeClass('mainMenuParentBtn');
			$(this.btn).addClass('mainMenuParentBtnFocused');	
		}else{
			$(this.btn).removeClass('subMenuParentBtn');
			$(this.btn).addClass('subMenuParentBtnFocused');
		}
		this.root.subMenuZindex++;
		this.childMenu.setStyles({'display':'block','visibility':'hidden','z-index':this.root.subMenuZindex});
		
		if(!this.width || !this.height ){
			this.width = this.childMenu.getFirst().getCoordinates().width;
			this.height = this.childMenu.getFirst().getCoordinates().height;
			this.childMenu.setStyle('height',this.height,'border');
			if(this.options.effect === 'slide' || this.options.effect === 'slide & fade'){
				if (this.subMenuType == 'initial' && this.options.orientation === 'horizontal' ) {
					this.childMenu.getFirst().setStyle('margin-top','0' );
					if(this.options.direction.y === 'down'){
						this.myEffect.set({ 'margin-top': - this.height });
					}else if(this.options.direction.y === 'up'){
						this.myEffect.set({ 'margin-top': this.height });
					}
				}else {
					if(this.options.direction.x === 'left'){
						this.myEffect.set({ 'margin-left': this.width });
					}else{
						this.myEffect.set({ 'margin-left': -this.width });
					}
				}
			}
		}
		this.matchWidth();
		this.positionSubMenu();
		
		if(this.options.effect === 'slide' ){
			this.childMenu.setStyles({'display':'block','visibility':'visible'});
			if (this.subMenuType === 'initial' && this.options.orientation === 'horizontal') {
				if(now){
					this.myEffect.set({ 'margin-top': 0 }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}else{
					this.myEffect.start({ 'margin-top': 0 }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}
			}else{
				if (now) {
					this.myEffect.set({ 'margin-left': 0 }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}else{
					this.myEffect.start({ 'margin-left': 0 }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}
			}
		}else if(this.options.effect === 'fade' ){
			if (now) {
				this.myEffect.set({'opacity': this.options.opacity}).chain(function(){	this.showSubMenuComplete();	}.bind(this));
			}else{
				this.myEffect.start({'opacity': this.options.opacity}).chain(function(){	this.showSubMenuComplete();	}.bind(this));
			}
		}else if(this.options.effect == 'slide & fade'){
			this.childMenu.setStyles({'display':'block','visibility':'visible'});
			this.childMenu.getFirst().setStyles({'left':0});
			if (this.subMenuType === 'initial' && this.options.orientation === 'horizontal') {
				if (now) {
					this.myEffect.set({ 'margin-top': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}else{
					this.myEffect.start({ 'margin-top': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
				}
			}else{
				if (now) {
					if (this.options.direction.x === 'right') {
						this.myEffect.set({ 'margin-left': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
					}else if (this.options.direction.x === 'left') {
						this.myEffect.set({ 'margin-left': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
					}	
				}else{
					if (this.options.direction.x === 'right') {						
						this.myEffect.set({ 'margin-left': -this.width, 'opacity': this.options.opacity });						
						this.myEffect.start({ 'margin-left': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
					}else if (this.options.direction.x === 'left') {
						this.myEffect.start({ 'margin-left': 0, 'opacity': this.options.opacity }).chain(function(){	this.showSubMenuComplete();	}.bind(this));
					}
				}
			}
		}else{
			this.childMenu.setStyles({'display':'block','visibility':'visible'}).chain(function(){	this.showSubMenuComplete(this);	}.bind(this));
		}
		this.childMenu.store('status','open');
		
	},
	
	showSubMenuComplete:function(){		
		this.options.onShowSubMenu_complete(this);
	},
	
	positionSubMenu: function(){
		this.options.onPositionSubMenu_begin(this);
		this.childMenu.setStyle('width',this.width) ;
		this.childMenu.getFirst().setStyle('width',this.width) ;
				
		//if any parent has bounced off a viewport edge, inherit that new direction
		if (this.subMenuType === 'subsequent') {
			if(this.parentSubMenu && this.options.direction.x != this.parentSubMenu.options.direction.x){
				if(this.parentSubMenu.options.direction.x === 'left' && this.options.effect && this.options.effect.contains('slide')){
					this.myEffect.set({ 'margin-left': this.width });	
				}
			}
			this.options.direction.x = this.parentSubMenu.options.direction.x;
			this.options.direction.xInverse = this.parentSubMenu.options.direction.xInverse;
			this.options.direction.y = this.parentSubMenu.options.direction.y;
			this.options.direction.yInverse = this.parentSubMenu.options.direction.yInverse;
		}

		var top;
		var overlap
		if(this.subMenuType == 'initial'){
			if(	this.options.direction.y === 'up'){				
				if(this.options.orientation === 'vertical'){
					top = this.btn.getCoordinates().bottom - this.height + this.options.tweakInitial.y ;
				}else{			
					top = this.btn.getCoordinates().top - this.height + this.options.tweakInitial.y ;
				}
				this.childMenu.style.top = top+ 'px';
			}else if(this.options.orientation == 'horizontal'){
				this.childMenu.style.top = this.btn.getCoordinates().bottom + this.options.tweakInitial.y + 'px';
			}else if(this.options.orientation == 'vertical'){
				top = this.btn.getPosition().y + this.options.tweakInitial.y ;				
				if((top + this.childMenu.getSize().y) >= $(document.body).getScrollSize().y){
					overlap = (top + this.childMenu.getSize().y) - $(document.body).getScrollSize().y  ;
					top = top - overlap - 20;
				}	
				this.childMenu.style.top = top+ 'px';
			}
			if(	this.options.orientation == 'horizontal'){
				this.childMenu.style.left = this.btn.getPosition().x + this.options.tweakInitial.x + 'px';
			}else if(this.options.direction.x == 'left'){
				this.childMenu.style.left = this.btn.getPosition().x - this.childMenu.getCoordinates().width + this.options.tweakInitial.x + 'px';
			}else if(this.options.direction.x == 'right'){
				this.childMenu.style.left = this.btn.getCoordinates().right + this.options.tweakInitial.x + 'px';
			}
		}else if(this.subMenuType == 'subsequent'){
			
			if(this.options.direction.y === 'down'){
				if( (this.btn.getCoordinates().top + this.options.tweakSubsequent.y+ this.childMenu.getSize().y) >= $(document.body).getScrollSize().y ){
					overlap =  (this.btn.getCoordinates().top + this.options.tweakSubsequent.y+ this.childMenu.getSize().y) -$(document.body).getScrollSize().y  ;
					this.childMenu.style.top = (this.btn.getCoordinates().top + this.options.tweakSubsequent.y) - overlap - 20+ 'px';
				}else{
					this.childMenu.style.top = this.btn.getCoordinates().top + this.options.tweakSubsequent.y + 'px';
				}
			}else if(this.options.direction.y === 'up'){
				if((this.btn.getCoordinates().bottom - this.height + this.options.tweakSubsequent.y)< 1){
					this.options.direction.y = 'down';
					this.options.direction.yInverse = 'up';
					this.childMenu.style.top = this.btn.getCoordinates().top + this.options.tweakSubsequent.y + 'px';
				}else{
					this.childMenu.style.top = this.btn.getCoordinates().bottom - this.height + this.options.tweakSubsequent.y + 'px';
				}
			}
			if(this.options.direction.x == 'left'){
				this.childMenu.style.left = this.btn.getCoordinates().left - this.childMenu.getCoordinates().width + this.options.tweakSubsequent.x + 'px';
				
				if( this.childMenu.getPosition().x < 0){					
					this.options.direction.x = 'right';
					this.options.direction.xInverse = 'left';
					this.childMenu.style.left = this.btn.getPosition().x + this.btn.getCoordinates().width + this.options.tweakSubsequent.x + 'px';
					
					if(this.options.effect === 'slide' || this.options.effect === 'slide & fade'){
						this.myEffect.set({ 'margin-left': -this.width, 'opacity': this.options.opacity });						
					}
				}
			}else if(this.options.direction.x == 'right'){
				this.childMenu.style.left = this.btn.getCoordinates().right + this.options.tweakSubsequent.x + 'px';
				var smRight = this.childMenu.getCoordinates().right;
				var viewportRightEdge = document.getCoordinates().width + window.getScroll().x;				
				if( smRight > viewportRightEdge ){
					this.options.direction.x = 'left';
					this.options.direction.xInverse = 'right';
					this.childMenu.style.left = this.btn.getCoordinates().left - this.childMenu.getCoordinates().width + this.options.tweakSubsequent.x + 'px'
					if (this.options.effect === 'slide' || this.options.effect === 'slide & fade') {
						this.myEffect.set({	'margin-left': this.width,	'opacity': this.options.opacity	});
					}
				}
			}
		}
		this.options.onPositionSubMenu_complete(this);
	}	
});

var pdocs;
var pshow;

function getAutoQuery(filters,mode){
	if($("searchbox").value == "") return;
	new Request.JSONP({
    url: 'http://search.digicon.gr/pulp.php',
	data: {
		query:$("searchbox").value,
		filter:filters,
		order:"0",
		mode:mode,
		popup:"yes"
	},
    onComplete: function(data){
		r=data.results;
		$("searchpopup").innerHTML="";
		
		if(r.length>0){
			for(var i=0;i<r.length;i++){
				$("searchpopup").grab(new Element("div",
					{
						'class': 'popper',
						'html':'<a href="'+r[i].path+'">'+r[i].title+'</a> '
					}
				
				));
			}
		}
		
		$("searchpopup").position({relativeTo:"searchbox",position:'bottomLeft'});
		$("searchpopup").fade("out");
		$("searchpopup").style.display="block";
		$("searchpopup").fade("in");
		
		
	
	}
}).send();

}

function getForumQuery(){
if(	$("query").value=="") return;
	var flts=[];
	var ord=0;
	var rmode="any";
	var trgt=0
	/*
	$$('.F').each(function(f){
			if(f.style.textDecoration=="line-through"){
				flts[flts.length]=f.rel;
			}
		});
	$$('.rad').each(function(r){
		if(r.checked){
			ord=r.value;
		}
	});
	$$('.rmode').each(function(r){
		if(r.checked){
			rmode=r.value;
		}
	});
	if($("checkgroup").checked){
		grp="yes";
	}
	*/
	new Request.JSONP({
    url: 'http://search.digicon.gr/pulpforum.php',
	data: {
		query:$("query").value,
		filter:flts.join(","),
		order:ord,
		mode:rmode

	},
    onComplete: function(data){
		$("loading").style.display="none";
		window.searchresults=data.results;
		$("searchpager").innerHTML="";
		$("searchpager").grab(new Element("span",
					{
						'class': 'spager',
						'html':'<a  href="#" onclick="$(\'resultscontainer\').dissolve();return false;">Κλεισιμο</a> '
					}
				
				));
		if(window.searchresults.length>6){
		var mod="";
		for(var i=0;i<window.searchresults.length/6;i++){
				if(i) mod="-";
				$("searchpager").grab(new Element("span",
					{
						'class': 'spager',
						'html':mod+'<a id="spager'+i+'" href="#" onclick="showForumResults('+i+'); return false;">'+(i+1)+'</a> '
					}
				
				));
		}
		}
		
		showForumResults(0);
		if(window.searchresults.length==0){
			$("results").innerHTML="Δεν βρέθηκαν αποτελέσματα";
			$("resultsheader").style.display="none";
		}else{
			$("resultscontainer").reveal();
			$("resultsheader").style.display="block";
			$("results").highlight("#EBEBEB");
		}
		
	
	}
}).send();
$('loading').position({relativeTo:"sub",position:'center'})
	
	$('loading').style.display="block";

}
function getQuery(){
	
	if(!$("results")){
		location.href="/searchresults.aspx?query="+$("searchbox").value;
	}
	var flts=[];
	var ord=0;
	var rmode="any";
	var grp="";
	$$('.searchfilter').each(function(f){
			if(f.style.textDecoration=="line-through"){
				flts[flts.length]=f.rel;
			}
		});
	$$('.rad').each(function(r){
		if(r.checked){
			ord=r.value;
		}
	});
	$$('.rmode').each(function(r){
		if(r.checked){
			rmode=r.value;
		}
	});
	if($("checkgroup").checked){
		grp="yes";
	}
	new Request.JSONP({
    url: 'http://search.digicon.gr/pulp.php',
	data: {
		query:$("searchbox").value,
		filter:flts.join(","),
		order:ord,
		mode:rmode,
		group:grp
	},
    onComplete: function(data){
		$("loading").style.display="none";
		window.searchresults=data.results;
		$("searchpager").innerHTML="";
		if(window.searchresults.length>6){
		var mod="";
		for(var i=0;i<=window.searchresults.length/6;i++){
				if(i) mod="-";
				$("searchpager").grab(new Element("span",
					{
						'class': 'spager',
						'html':mod+'<a id="spager'+i+'" href="#" onclick="showResults('+i+');new Fx.Scroll(window).toElement(\'breadcrumb\'); return false;">'+(i+1)+'</a> '
					}
				
				));
		}
		}
		
		showResults(0);
		if(window.searchresults.length==0){
			$("results").innerHTML="Δεν βρέθηκαν αποτελέσματα";
			$("resultsheader").style.display="none";
		}else{
			$("resultsheader").style.display="block";
			$("results").highlight("#EBEBEB");
		}
		
	
	}
}).send();
$('loading').position({relativeTo:"results",position:'center'})
	
	$('loading').style.display="block";

}
function showResults(num){
	
	$("results").innerHTML="";
	$$("#searchpager a").each(function(el,i){
		el.style.color="#C23131";
		el.style.backgroundColor="";
	})
	if($("spager"+num)){
		$("spager"+num).style.color="white";
		$("spager"+num).style.backgroundColor="#C23131";
	}
	for(var i=0;i<6;i++){
		if(!window.searchresults[num*6+i]){
			break;
		}
		var d=window.searchresults[num*6+i];
		var paths=d.path.split("/");
		var htmlpath="";
		var realpath="http://www.pulp.gr";
		for(var p=1;p<paths.length-1;p++){
			realpath=realpath+"/"+paths[p];
			htmlpath=htmlpath+"<a href=\""+realpath+".aspx\" >"+paths[p]+"</a>";
			if(p!=paths.length-2){
				htmlpath=htmlpath+" / ";
			}
		}
		if(d.image=="") d.image="/App_Themes/ipulp/slogo.jpg";
		new Element("div",
			{
			'class': 'art2',
			'html':"<div class=\"bimg\"><a href=\""+d.path+"\"><img border=\"0\" src=\""+d.image+"?maxSideSize=96\"/></a></div><div style=\"margin-bottom:4px;height:70px;width:500px;float:right;border:0;text-align:left;\"> <h6><a href=\""+d.path+"\">"+d.title+"</a></h6>"+d.summary+"</div><div class=\"path\">"+htmlpath+"</div>"
			}
			
			).inject($("results"));
	
	}
	

}
function showForumResults(num){
	$("results").innerHTML="";
	$$("#searchpager a").each(function(el,i){
		el.style.color="#C23131";
		el.style.backgroundColor="";
	})
	if($("spager"+num)){
		$("spager"+num).style.color="white";
		$("spager"+num).style.backgroundColor="#C23131";
	}
	for (var i = 0; i < 6; i++) {
		if (!window.searchresults[num * 6 + i]) {
			break;
		}
		var d = window.searchresults[num * 6 + i];
		if (d.docid == "") {
		
		new Element("div", {
			'class': 'art3',
			'html': "<div style=\"margin-bottom:4px;border:0;text-align:left;\"> <h6><a href=\"/Forums.aspx?forumid=" + d.forumid + "&threadid=" + parseInt(d.path.split('/')[1], 10) + "\">" + d.subject + "</a><br/><a href=\"/Forums.aspx?forumid=" + d.forumid + "\">" + d.forumname + "</a></h6>" + d.snips + "</div>"
		}).inject($("results"));
		}else{
		new Element("div", {
			'class': 'art3',
			'html': "<div style=\"margin-bottom:4px;border:0;text-align:left;\"> <h6><a href=\"" + d.docid +"\.aspx\">" + d.subject + "</a><br/><a href=\"" + d.docid + "\.aspx\">" + d.forumname + "</a></h6>" + d.snips + "</div>"
		}).inject($("results"));
			
			
		}
	}
	

}
var panelCache={};
var lastPostID;

function startFade(sender,args){
		
		var evarg="";
		args.get_request().get_body().split('&').each(function(el,i){
			var temp=el.split("=");
			if(temp[0]=="__EVENTARGUMENT") 	evarg=temp[1];
		});
		
		if(args.get_postBackElement()==null)return;
		if(panelCache[args.get_postBackElement().id+evarg]){
			$(panelCache[args.get_postBackElement().id+evarg].id).set('html',panelCache[args.get_postBackElement().id+evarg].get("html"))
			new Fx.Scroll(window).toElement($(panelCache[args.get_postBackElement().id+evarg].id));
			$(panelCache[args.get_postBackElement().id+evarg].id).highlight("#EBEBEB");
			args.set_cancel(true);
			
		}else{
		$('loading').position({relativeTo:args.get_postBackElement().id,position:'center'})
		$('loading').style.display="block";
		
		lastPostID=args.get_postBackElement().id+evarg;
		}
}
function startFader(sender,args){
	$('loading').position({relativeTo:$("Fader").id,position:'center'})
	$('loading').style.display="block";
	
}

function stopFade(sender,args){
	
	
	if(args.get_panelsUpdated().length>0){
		if(!panelCache[lastPostID])
			panelCache[lastPostID]={};
		panelCache[lastPostID]=$(args.get_panelsUpdated()[0]).clone(true,true);
		//new Fx.Scroll(window).toElement(args.get_panelsUpdated()[0]);
		$('loading').style.display="none";
		args.get_panelsUpdated()[0].highlight("#EBEBEB");
	}
	$$(".showcase").each(function(el,i){
		el.set('tween', {duration: 300});

		el.addEvent("mouseover",function(){
			
			this.tween("background-color","#ecebe7");
		});
		el.addEvent("mouseout",function(){
			this.tween("background-color","#FCFAF7");
		});
		el.fireEvent("mouseout");
		el.addClass("showcased");
		el.removeClass("showcase");
		
	});
	
	
}
function stopFader(sender,args){
		//new Fx.Scroll(window).toElement("Fader");
		$('loading').style.display="none";
		$('Fader').highlight("#EBEBEB");
	
}

function scroller(el){
	var selectedPosX = 0;
	  	var selectedPosY = 0;
  		var theElement=$(el);            
  		while(theElement != null){
    			selectedPosY += theElement.offsetTop;
    			theElement = theElement.offsetParent;
  		}
                        		      
 		window.scrollTo(0,selectedPosY-100);


}
function setPage(id,first){
		pshow=$("mainbody");
		var tw=new Fx.Tween("mainbody",{duration:1000});
		if(!first){
			new Fx.Scroll(window).toElement("menuT");			
		tw.set("opacity","0.0");
		}
		if(pdocs[id]){
			pshow.innerHTML="";
			pshow.grab($(pdocs[id]).clone());
		}
		if(!first){
		tw.start("opacity","1.0");
		}
		if(pdocs.length<2){return;}
		for(var i=0; i < pdocs.length;i++){
			$("sp"+i).style.color="#C23131";
			$("sp"+i).style.backgroundColor="";
		}
		$("sp"+id).style.backgroundColor="#C23131";
		$("sp"+id).style.color="white";
	}
	var splitcounter=5;
	var ptips;
function splitContent(){
		ptips=new Array();
		var counter=0;
		var pages=0;
		pdocs=new Array();
		var prev;
		var pager=$("pulppager");
		if($$("#mainbody .nosplit").length){
			
			return;
		}else if($$("#mainbody .split").length){
			pdocs[pages]=new Element("div");
			var temp=$("mainbody").getChildren();
			var childs;
			if(temp.length==1){
				
				childs=$A(temp[0].childNodes);
				
				}else{
			childs=$A($("mainbody").childNodes);	
				}
			childs.each(function(el,i){
				if($(el).tagName){
				var myel=null;
				if(el.hasClass("split")){ 
					myel=el;
					}else{
				myel=el.getElement(".split");
				}
				if(myel){
				pages++;
				new Element("div",
			{
			'class': 'art2',
			'style':'padding-right:5px;width:565px;',
			'html':"<div style=\"padding-left:4px;text-align:right;\">Επόμενο: <a href=\"javascript:setPage("+(pages)+",false);\">"+myel.innerHTML+"</a></div>"
			
			}
			
			).inject(pdocs[pages-1]);
			prev=pdocs[pages-1].getElement(".split");
			if(prev){
				prev=pdocs[pages-1].getElement(".split").innerHTML;
			
			}else{
				if(pages==1){
					prev="Πρόλογος";
				}
			
			}
			ptips[pages-1]=prev;
			pdocs[pages]=new Element("div");
			new Element("div",
			{
			'class': 'art2',
			'style':'padding-left:5px;width:565px;',
			'html':"<div style=\"padding-left:4px;text-align:left;\">Προηγούμενο: <a href=\"javascript:setPage("+(pages-1)+",false);\">"+prev+"</a></div>"
			
			}
			
			).inject(pdocs[pages]);
				}
			}
			pdocs[pages].grab(el);
				
			});
			
		
		}else{
		hack=$$("#mainbody p")
		var temp=document.createElement("div");
		for(var i=0;i<hack.length;i++){
		if(counter==splitcounter){
			counter=0;
			pdocs[pages]=temp;
			pages++;
			var temp=document.createElement("div");
		}
		if(hack[i].innerHTML != null){
			if( hack[i].innerHTML.length > 64  ){
				counter++;	
			}else if(hack[i].getElements("img").length > 0){
				counter++;
			}
			temp.appendChild(hack[i]);
			
		}
		}
		}
		if(counter>0){
				pdocs[pages]=temp;
		}
		var num;
		if(pages>0){
		for(i=0;i<pdocs.length;i++){
			temp=document.createElement("span");
			num=i+1;
			if(i==0){
				temp.innerHTML="<a href=\"javascript:setPage("+i+",false);\" title=\""+ptips[i]+"\" class=\"tooltip2\"><span id=\"sp"+i+"\" style=\"background-color:#C23131;color:white;font-size:14px;padding:2px;\">"+num+"</span></a>";
			}else{
				
				temp.innerHTML=" - <a href=\"javascript:setPage("+i+",false);\"  title=\""+ptips[i]+"\" class=\"tooltip2\"><span id=\"sp"+i+"\" style=\"color:#C23131;font-size:14px;padding:2px;\">"+num+"</span></a>";
			}
			pager.appendChild(temp);
		}
		
		}
		

		setPage(0,true);
		
		
		
		
	}

function popToken(query,imdb,website,el,mode){
	
	var myquery=query.trim();
	
	new Request.JSONP({
    url: 'http://search.digicon.gr/pulp.php',
	data: {
		query:myquery,
		order:"0",
		mode:mode,
		popup:"yes"
	},
    onComplete: function(data){
		r=data.results;
		var more="";
		var did=null;
		var tid=null;
		if($("docID")) did=$("docID").innerHTML; 
		if($("templateID")) tid=$("templateID").innerHTML; 
		
		$("searchpopup").innerHTML="";
		more+='<div class="popper" style="text-align:center;" >';
		if(website){
			more+='<a href="'+website+'" target="_blank" > <img src="/App_Themes/ipulp/go_home.gif"/> Επίσημη σελίδα</a>';
		}
		more+='<a href="/searchresults.aspx?mode='+mode+'&query='+query+'"> <img src="/App_Themes/ipulp/go_pulp.gif"/> δείτε στο Pulp</a>';
	
		more+='<a href="http://www.google.com/search?q='+query+'" target="_blank"> <img src="/App_Themes/ipulp/go_google.gif"/> δείτε στο Google</a>';
		
	$("searchpopup").innerHTML+=more+"</div>";	
		
	
		var sep=true;
		var mystyle;
		if(r.length>0){
			for(var i=0;i<r.length;i++){
				if(did==r[i].doc_id)
					continue;
				mystyle="";
				if(sep){
					$("searchpopup").innerHTML+="<div class=\"popper\"><hr/></div>";	
					sep=false;
				}
				if(r[i].dtype!=tid){
					mystyle="style=\"color:#DADADA;\"";
				}
				$("searchpopup").grab(new Element("div",
					{
						'class': 'popper',
						'html':'<a href="'+r[i].path+'" '+mystyle+'> '+r[i].title+'</a> '
					}
				
				));
			}
		}
		
	$("searchpopup").position({relativeTo:el,position:'bottomLeft'});
	$("searchpopup").fade("out");
	$("searchpopup").style.display="block";
	$("searchpopup").fade("in");
	
	//$("searchpopup").noclose=true;
	$("loading").style.display="none";
		
	
	}
}).send();
	$('loading').position({relativeTo:el,position:'center'})
	
	$('loading').style.display="block";	
			
	
}
	
function searchFix(){
	$$(".searchHome").each(function(el,i){
		
			
		var	el2=el.getElement("a");
		if(el2)
		el.innerHTML="<a href=\"#\" onclick=\"popToken('"+el2.innerHTML+"',false,'"+el2.href+"',this,'phrase');return false;\" >"+el2.innerHTML+"</a>";
		
		
		el.getElements("span").each(function(el2,i){
			el2.innerHTML="<a href=\"#\" onclick=\"popToken('"+el2.innerHTML+"',false,null,this,'phrase');return false;\" >"+el2.innerHTML+"</a>";
		});
		
	});
	
	$$(".searchImdb").each(function(el,i){
		var temp=new Array();
		el.innerHTML.split(",").each(function(token,ini){
			temp[temp.length]="<a href=\"#\" onclick=\"popToken('"+token+"',true,null,this,'phrase');return false;\" >"+token+"</a>";
		});
		el.innerHTML=temp.join(",");
	});
	
	$$(".searchPlain").each(function(el,i){
		var temp=new Array();
		el.innerHTML.split(",").each(function(token,ini){
			if(token.split(" ").length > 1){
			 temp[temp.length]="<a href=\"#\" onclick=\"popToken('"+token+"',false,null,this,'phrase');return false;\" >"+token+"</a>";
			
			}else{
				temp[temp.length]="<a href=\"#\" onclick=\"popToken('"+token+"',false,null,this,'any');return false;\" >"+token+"</a>";
			
			}
		});
		el.innerHTML=temp.join(",");
	});
	$$(".searchKeys").each(function(el,i){
		var temp=new Array();
		var all="";
		el.innerHTML.split(",").each(function(token,ini){
			temp[temp.length]="<a href=\"#\" onclick=\"popToken('"+token+"',false,null,this,'any');return false;\" >"+token+"</a>";
			all=all+" "+token;
		});
		el.innerHTML=temp.join(",");
		
		new Request.JSONP({
    url: 'http://search.digicon.gr/pulp.php',
	data: {
		query:all,
		order:"0",
		mode:'any',
		single:'yes',
		related:'yes'
	},
    onComplete: function(data){
		$("related").innerHTML="";
		r=data.results;
		var more="";
		
		if(r.length>0){
			$("related").innerHTML='<div style="text-align:center;"><img src="/App_Themes/ipulp/headers/sxetikarthra.jpg"/></div>';
			for(var i=0;i<r.length;i++){
				
		var d=r[i];
		if($("docID")){
			if(d.doc_id == $("docID").innerHTML)
				continue;
		}	
		var paths=d.path.split("/");
		var htmlpath="";
		var realpath="http://www.pulp.gr";
		for(var p=1;p<paths.length-1;p++){
			realpath=realpath+"/"+paths[p];
			htmlpath=htmlpath+"<a href=\""+realpath+".aspx\" >"+paths[p]+"</a>";
			if(p!=paths.length-2){
				htmlpath=htmlpath+" > ";
			}
		}
		var newel=new Element("div",
			{
			'class': 'showcase',
			'style': "height:auto;width:320px;padding:1px;text-align:left;margin-left:3px;margin-top:3px;",
			'html':"<h6 style=\"text-align:left\"><a href=\""+d.path+"\">"+d.title+"</a></h6>"
			}
			
			);
			$("related").grab(newel);	
			
			
				
			}
		$("related").innerHTML+='<div style="margin-top:12px;margin-right:4px;text-align:right;"><a style="font-weight:normal;" href="/searchresults.aspx?query='+all+'">Περισσότερα άρθρα</a></div>'	
		}
		$$(".showcase").each(function(el,i){
		el.set('tween', {duration: 300});

		el.addEvent("mouseover",function(){
			
			this.tween("background-color","#ecebe7");
		});
		el.addEvent("mouseout",function(){
			this.tween("background-color","#FCFAF7");
		});
		el.fireEvent("mouseout");

	});

		
	
	}
}).send();
	});

}	
	
function sfilter(fl){
	if(fl==-1){
		$$('.searchfilter').each(function(f){
				f.style.textDecoration="line-through";
				f.style.color="gray";
		});
	}
	if(fl==0){
		$$('.searchfilter').each(function(f){
				f.style.textDecoration="none";
				f.style.color="#D14343";
		});
	}
	


}
var poptimeout= 0;
var currentFader=null;
function initSmallFader(start){
	var switchAcc = function(){
		start.getElement(".next").fireEvent("click");

	}
	if(!start) return;
	start.getElement(".previous").position({relativeTo:start,offset:{x:-100,y:0}
});
	start.getElement(".previous").fade(0.0);
	start.getElement(".previous").addEvent("click",function(){
		if(start.currentSlide==start.getElements(".miniContent")[0]){
			start.currentSlide.fade(0.0);
			start.currentSlide=start.getElements(".miniContent")[start.getElements(".miniContent").length-1];
			start.currentSlide.fade(1.0);
			
		}else{
			start.currentSlide.getPrevious().fade(1.0);
			start.currentSlide.fade(0.0);
			start.currentSlide=start.currentSlide.getPrevious();
		}
		
	});
	start.getElement(".next").position({relativeTo:start,offset:{x:100,y:0}
});
	start.getElement(".next").fade(0.0);
	start.getElement(".next").addEvent("click",function(){
		
		if(start.currentSlide==start.getElements(".miniContent")[start.getElements(".miniContent").length-1]){
			start.currentSlide.fade(0.0);
			start.currentSlide=start.getElements(".miniContent")[0];
			start.currentSlide.fade(1.0);
			
		}else{
			start.currentSlide.getNext().fade(1.0);
			start.currentSlide.fade(0.0);
			start.currentSlide=start.currentSlide.getNext();
		}
		
	});
	start.getElements(".miniContent").each(function(div,i){
		if(div==start.getElements(".miniContent")[0]){ 
		start.currentSlide=div;
		return;
		}
		div.fade(0.0);
	});
	start.addEvent("mouseover",function(){
			$clear(start.acctimer);
			this.getElement(".previous").style.display="block";
			this.getElement(".next").style.display="block";
			
			this.getElement(".previous").fade(1.0);
			this.getElement(".next").fade(1.0);
			
			
	});
	start.addEvent("mouseout",function(){
			$clear(start.acctimer); start.acctimer=switchAcc.periodical(8000, {});
			this.getElement(".previous").fade(0.0);
			this.getElement(".next").fade(0.0);
			this.getElement(".previous").style.display="none";
			this.getElement(".next").style.display="none";
			
	});
	
	start.acctimer=switchAcc.periodical(8000, {});	

}

var acctimer;
var acclen;

function initFader(){
	var switchAcc = function(){
		if(currentFader==$$(".faderHeader")[acclen-1]){
			$$(".faderHeader")[0].fireEvent("click");
		}else{
			currentFader.getNext().fireEvent("click");
		}

	}
	$$(".faderContent").each(function(div,i){
		div.set('tween', {duration: 300});
	});
	$$(".faderContent").each(function(div,i){
		div.set('tween', {duration: 600});

		var temp=div.getElement(".faderHeader");
		temp.addEvent("click",function(){
			$clear(acctimer); 
			
			$$(".faderContent").each(function(dv,i){
				dv.fade(0.0);
				
			});
			div.fade(1.0);
			currentFader=this;
			$$(".faderHeader").each(function(el,i){
				if(el==currentFader){
					el.fade(1.0);
					
				}else{
					el.fade(0.6);
					
				}
				
			});
			acctimer=switchAcc.periodical(8000, {});
			
			
		});
		temp.addEvent("mouseover",function(){
			//el.style.border="4px solid #D0D0D0";
			temp.fade(1.0);
		});
		temp.addEvent("mouseout",function(){
			if(temp==currentFader)return;
			temp.fade(0.6);
			//el.style.border="4px solid black";
		});
		temp.fade(0.6);
		$("faderPager").grab(temp);
		temp.style.position="relative";
		temp.style.display="inline";
		
		div.fade(0.0);
	});
	
	$$(".faderHeader")[0].fireEvent("click");
	acclen=$$(".faderHeader").length;
	$$('.zonePop')[0].addEvent("mouseover",function(){ $clear(acctimer); });
	$$('.zonePop')[0].addEvent("mouseout",function(){ $clear(acctimer); acctimer=switchAcc.periodical(8000, {}); });
	
	acctimer=switchAcc.periodical(8000, {});

}
var s2;
var player;
function verr(msg){
			if(window.vcur){
				vcur.getElement("img").style.opacity="0.4";
				vcur.getElement("a").style.color="black";
				vcur.getElement("a").innerHTML="Το τρέιλερ δεν είναι διαθέσιμο";
				}
}
function playerReady(obj) {
	player = document.getElementById(obj['id']);
	player.addModelListener("ERROR","verr"); 
	window.winit=false;
	var temp=$$('.vitem');
	var pg=$("vpager");
	pg.current=null;
	if(temp.length){
			temp.each(function(div,i){
				div.fade(0.6)
				div.addEvent("mouseover",function(){
					this.fade(1.0);
				});
				div.addEvent("mouseout",function(){
					if(pg.current==this) return;
					this.fade(0.6);
				});
			
			})
			
		$(temp[0]).onclick();
		$(temp[0]).fade(1.0);
	}
	
	if($$(".vitem").length==0){
			player.sendEvent("LOAD","http://unix.compupress.gr/pulp.flv");
			player.sendEvent("PLAY","false");
			window.winit=true;
	}
	
}
function playVideo(src,el){
		window.vcur=el;
		var pg=$("vpager");
		if(pg.current==el) return;
		pg.current=el;
		
		$$(".vitem").each(function(div,i){
			if(pg.current==div) return;
			div.fade(0.6);
		});
		$(el).fade(1.0);
		
		player.sendEvent("LOAD",src);
		if(window.winit){
			player.sendEvent("PLAY","true");
			
		}else{
		player.sendEvent("PLAY","false");
		window.winit=true;
		}
}
var daylist=['Κυριακή','Δευτέρα','Τρίτη','Τετάρτη','Πέμπτη','Παρασκευή','Σάββατο'];
var mlist=['Ιανουάριος','Φεβρουάριος','Μαρτιος','Απρίλιος','Μαιος','Ιούνιος','Ιούλιος','Αυγουστος','Σεμπτεμβριος','Οκτωμβριος','Νοεμβριος','Δεκέμβριος'];
function fixForum(){
	
	new DatePicker(".dpicker",{allowEmpty:true,days:daylist,months:mlist});
	var fcookie=new Hash.Cookie('forums', {duration: 3600});
	var last=fcookie.get("last");
	var lastmax=0;
	$$(".forumHeader").each(function(el,i){
		el.addEvent("click",function(){
			this.getNext().reveal();
			this.dissolve();
			fcookie.set(el.id,0);
			fcookie.save();
		});
		
	});
	$$(".forumContent").each(function(el,i){
		el.getElements(".LastPost .PostTime").each(function(tm,i){
			var latest=Date.parse(tm.innerHTML.clean().replace("(","").replace(" AM)","").replace(" PM)",""));
			if(latest>lastmax) lastmax=latest;
			if( latest > fcookie.get(tm.id)){
				
				tm.style.fontSize="14px";
				tm.style.color="#E36C26";
				tm.getParent().getParent().style.backgroundColor="#F3F1E9";
				
				var temp=el.getElement(".Info .GroupName");
				if(temp){
				temp.style.color="#F7870C";
				temp=el.getPrevious();
				
				temp.style.color="#F7870C";
				}
				
				
			}
		
		});
		fcookie.save();
		closelink=new Element("a",{
			"html":"Κλείσιμο του παρακάτω φόρουμ",
			"style":"color:#CCCCCC;cursor:pointer;"
		});
		closelink.addEvent("click",function(){
			el.dissolve();
			el.getPrevious().reveal();
			fcookie.set(el.getPrevious().id,1);
			fcookie.save();
		});
		if(el.getElement("td.ForumName")){
		el.getElement("td.ForumName").innerHTML="";
		el.getElement("td.ForumName").grab(closelink);
		if(fcookie.get(el.getPrevious().id)){ closelink.fireEvent("click");};
		}
	});
	if($("forumId")){
		fcookie.set($("forumId").value,lastmax);
		fcookie.save();
		//alert($("forumId").value+" "+lastmax);
	}
	
	

}

window.addEvent('load', function() {
var lheight=0;
	var lwidth=0;
	$$('.light img').each(function(el){
		el.addEvent("mouseover",function(){
			this.fade(1.0);
		});
		el.addEvent("mouseout",function(){
			this.fade(0.6);
		});
		el.fireEvent("mouseout");
    if(parseInt(el.getStyle("height"))>lheight) lheight=parseInt(el.getStyle("height"));
	lwidth=lwidth+8+el.width;
	});
	if(lheight && $("gslider")){
		
		$("gslider").setStyle("height",lheight+20);
		$("gslider").setStyle("width",lwidth);
		new Scroller("gcontainer",{area:50}).start();
	}
});
//BLOOD BG CLICKABLE

/*window.addEvent("click",function(e){
	evt = e || window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // Safari bug
	targ = targ.parentNode;
	if(targ.id=='form1') window.open("http://furious.adman.gr/click?webspace=3248&auto=1");
	
 
});
*/

window.addEvent('domready', function() {
//initImageZoom({rel: 'lightbox',draggable:false,overlay:true});

//if($$(".vitem").length<2) $("vpager").style.display="none";
var box = new multiBox('mbox');

//$('logo').position({relativeTo:$('banner'),offset:{x:-450,y:12},edge:'center'});
//if($$(".vitem").length<2) $("vpager").style.display="none";
if($("video")){
	s2 = new SWFObject("/App_Themes/ipulp/jw/player.swf","mpl","320","240","7");
	s2.addParam("allowfullscreen","true");
	s2.addParam("wmode","transparent");
	//s2.addVariable("file","MyPlayList.aspx?MM=false&plref&2;id=1");
	s2.addVariable("displayheight","200");
	s2.addVariable("backcolor","0xD14343");
	s2.addVariable("frontcolor","0xF3F1E9");
	s2.addVariable("lightcolor","0xD14343");
	s2.addVariable("width","320");
	s2.addVariable("height","240");
	s2.addVariable("wmode","transparent");
	s2.addVariable("javascriptid","mpl");
	s2.addVariable("enablejs","true");

	s2.write("vcontent");
}
	if(Browser.Engine.trident){
      new MenuMatic({id:"menuElem",tweakInitial:{x:-18,y:0},tweakSubsequent:{x:-24,y:0},duration:50}); 
	  }else{
	  new MenuMatic({id:"menuElem",tweakInitial:{x:0,y:-2},tweakSubsequent:{x:0,y:0},duration:50}); 
	  
	  }
	
	
	$$('.searchfilter').each(function(f){
				f.addEvent("click",function(event){
					if(this.style.textDecoration=="none" || this.style.textDecoration=="" ){
						this.style.textDecoration="line-through";
						this.style.color="gray";
					}else{
					this.style.textDecoration="none";
					this.style.color="#D14343";
				}
				return false;
				});
		});
	if($("results")){
		$("searchbox").addEvent("keypress",function(event){
			if (null == event)
			event = window.event ;
			
			if (event.event.keyCode==13){
			getQuery();
			return false;
			}
		}
		);
		var ur=new URI(window.location.href);
		var startquery=ur.getData("query");
		var startfilter=ur.getData("filter");
		var startmode=ur.getData("mode");
		
		
		if(startfilter){
			var flts=startfilter.split(",");
			$$(".searchfilter").each(function(el,i){
				if(flts.contains(el.rel)){
					el.style.textDecoration="line-through";
					el.style.color="gray";
				}
			});
		}
		if(startmode){
			$$(".rmode").each(function(el,i){
				if(el.value==startmode){
					el.checked=true;
				}
			});
		}
		if(startquery){
			$("searchbox").value=startquery;
			getQuery();
		}
	
	}else{
		$("searchbox").addEvent("keypress",function(evt){
			 var charCode = evt.code;
      

			
			if (charCode==13){
			location.href="/searchresults.aspx?query="+$("searchbox").value;
			return false;
			}
			if (charCode!=32){
			poptimeout=true;
			return true;
			}
			if(!poptimeout){
				return true;
			}
			if($("searchbox").value.trim() == "") return true;
			var searchmode="any";
			var searchfilters="";
			if($("searchfilters"))
				searchfilters=$("searchfilters").value;
			if($("searchmode"))
				searchmode=$("searchmode").value;
			$("searchpopup").noclose=false;	
			getAutoQuery(searchfilters,searchmode);
			poptimeout=false;
		}
		);
		document.body.addEvent("click",function(e){
			if(! $("searchpopup").noclose)
				$("searchpopup").fade("out");
				
				$("searchpopup").style.display="none";
	
			$("searchpopup").noclose=false;	
			
		});
		searchFix();
	
	}
	if($("mainbody")){
		splitContent();
	}
	$$('.inputSearch').each(function(el){
		if(el.value == "") el.fade(0.4);
		el.addEvent("focus",function(){
			this.fade(0.9);
		});
		el.addEvent("blur",function(){
			if(this.value == "")
			this.fade(0.4);
		});
		el.fireEvent("blur");
});		
	
	
new Tips('.tooltip');

 }); 

var adzones={
			"contact":{'300':28,'728':29,'468':30},
			"thanks":{'300':28,'728':29,'468':30},
			"searchresults":{'300':28,'728':29,'468':30},
			"aboutus":{'300':28,'728':29,'468':30},
			"disclaimer":{'300':28,'728':29,'468':30},
			"register":{'300':28,'728':29,'468':30},
			"news":{'300':71,'728':74},
			"home":{'300':28,'728':29,'468':30},
			"cinema":{'300':4,'728':2,'468':6,'R300':5,'R728':3,'R468':7},
			"tv-series":{'300':76,'728':77,'468':94,'R300':75,'R728':78,'R468':93},
			"books":{'300':80,'728':81,'468':82,'R300':79,'R728':95,'R468':83,'301':96},
			"comics":{'300':22,'728':24,'468':26,'R300':23,'R728':25,'R468':90},
			"manga":{'300':18,'728':16,'468':19,'R300':17,'R728':15,'R468':20},
			"videogames":{'300':8,'728':10,'468':12,'R300':9,'R728':11,'R468':13,'301':97},
			"tabletop-games":{'300':84,'728':86,'468':88,'R300':85,'R728':87,'R468':89,'301':98},
			"account":{'300':28,'728':29,'468':30},
			"naruto":{'300':18,'728':16,'468':19}

			};
function printZone(z){
		var u=new URI(location.href);
		
		if(u.get("directory")=="/"){
			if(u.get("file")==null || u.get("file")=="default.aspx"){
				OA_show((adzones["home"])[z]);
				return;
				
				
			}
			
			for(i in adzones){
				
				if(u.get("file").toLowerCase() ==i+'.aspx'){
					//console.log((adzones[i])[z]);
					OA_show((adzones[i])[z]);
					return;
				}
				
			}
		}else{
			for(i in adzones){
				if(u.get("directory").split("/")[1].toLowerCase() == i){
					//console.log((adzones[i])['R'+z]);
					OA_show((adzones[i])['R'+z]);
					return;
				}
				
			}
		}
		
	
}
