/*
	TODO:
		- Compact this
*/
var codeOk = false;

var menuTimer, zoomWindow, zoomWindowDoc, zoomWindowLoading;
window._notOnFocus = false;

if(RPCProxy) {
	Ajax.RPC.proxy = RPCProxy;
}

function handleMenu( node, e ) {
	e = Event.fix(e);
	Node.toggleClass( node,"hover");
	if( e.type == "mouseover" ) {
		try{ $("q").blur(); } catch (ex) {}
	}
}
Event.add( window, "resize", function() { 	  	
	Tooltip.pos();				
	Menu.hide();
	Zoom.pos();
});

Event.add( window, "unload", function() { 
	// IE Memory leak fixe
	if( System.browser.ie ) {
		Tooltip.instances.forEachBind( function() {
			this._tooltip = null;
		});
	}	
	if( System.browser.ie6 )  {
		var allNodes = $T( "li", "menu");
		forEachBind( allNodes, function() {
			if( this.shield ) {
				Node.remove( this.shield);
				this.shield = null;
			}
		});
	}
});

DEBUG = true;

// Merchant Map
Map		= {
	lat		: 38.169114,
	lon		: 23.664551,
	zoom	: 6,
	map		: null,
	marker	: null,
	markers	: [],
	icon	: null,
	usericon: null,
	userLat	: "",
	userLon : "",
	userLoc : "",

	initialize	: function()	{
		var point 					= new GLatLng(Map.lat, Map.lon);
		
		Map.icon 					= new GIcon();
		Map.icon.image 				= "/img/icon.png";
		Map.icon.shadow 			= "http://www.google.com/mapfiles/shadow50.png";
		Map.icon.iconSize 			= new GSize(20, 34);
		Map.icon.shadowSize 		= new GSize(37, 34);
		Map.icon.iconAnchor 		= new GPoint(9, 34);
		Map.icon.infoWindowAnchor 	= new GPoint(9, 2);
		Map.icon.infoShadowAnchor 	= new GPoint(18, 25);

		Map.map = new GMap2($("map"));
		Map.map.addControl(new GLargeMapControl());
		Map.map.addControl(new GMapTypeControl());
		Map.map.setCenter(point, Map.zoom);

		Map.map.enableScrollWheelZoom(); 	/* Zoom using the wheel */
		Map.loadShops();
	},
	
	loadShops	: function()	{
		var point,mark;
		var bounds = new GLatLngBounds();
		
		merchantPoints.each(function(item, k){
			Map.markers[k] 	= mark;
			var point		= new GLatLng(parseFloat(item[1]), parseFloat(item[2]));
			Map.markers[k] 	= new GMarker( point, { 'icon': Map.icon, 'title': item[0] });
		
			bounds.extend(point);
			
			GEvent.addListener(Map.markers[k], "click", function() {
				var html = [];
				
				html.push('<h5 style="font-size: 13px; margin: 10px 0">'+item[0]+'</h5>');
				html.push('<a class="zoom-map" style="font-size:11px;" href="javascript:void(0);" onclick="Map.map.setZoom(30);">Εστιάστε στην περιοχή</a>');
				Map.markers[k].openInfoWindowHtml(html.join(''));
			});

			Map.map.addOverlay(Map.markers[k]);
		});
		
		if(Map.userLat != "" && Map.userLon != "" && Map.userLoc != "")	{
			Map.usericon 					= new GIcon();
			Map.usericon.image 				= "/img/user_icon.png";
			Map.usericon.shadow 			= "http://www.google.com/mapfiles/shadow50.png";
			Map.usericon.iconSize 			= new GSize(20, 34);
			Map.usericon.shadowSize 		= new GSize(37, 34);
			Map.usericon.iconAnchor 		= new GPoint(9, 34);
			Map.usericon.infoWindowAnchor 	= new GPoint(9, 2);
			Map.usericon.infoShadowAnchor 	= new GPoint(18, 25);

			var point			= new GLatLng(Map.userLat, Map.userLon);
			var html 			= [];
		
			bounds.extend(point);
			html.push('<h5 style="font-size: 13px; margin: 10px 0">Η τρέχουσα τοποθεσία σας</h5>');

			Map.marker			= new GMarker(point, {
				'icon'	: Map.usericon,
				'title'	: Map.userLoc
			});
			
			GEvent.addListener(Map.marker, "click", function() {
				Map.marker.openInfoWindowHtml(html.join(''));
			});
	
			Map.map.addOverlay(Map.marker);
			Map.marker.openInfoWindowHtml(html.join(''));
		//	Map.map.setCenter(point,7);
		}
		
		var clat = (bounds.getNorthEast().lat() + bounds.getSouthWest().lat()) /2;
		var clng = (bounds.getNorthEast().lng() + bounds.getSouthWest().lng()) /2;
		
		Map.map.setCenter(new GLatLng(clat,clng));
		Map.map.setZoom(Map.map.getBoundsZoomLevel(bounds)-1);	
	}
};

// Poll {}
Poll	= {
	votespace	: 40,
	
	initialize	: function() {
		this.uid	= parseInt(Cookie.get('vote_uid'));
	},
	
	_initLoader	: function() {
		if(this.loader){
			return this;
		}
		var container = $('poll-content').makePositioned();
		this.loader = $C('div').
		setProperty('id', 'poll-loader').		
		setStyles(container.getDimensions()).
		setOpacity(0.95).
		injectBefore(container.getFirst());
	},
	
	_hideLoader	: function() {
		if(!this.loader) {
			return this;	
		}
		
		this.loader.hide().remove();
		// FIXME: bug?
		this.loader = null;		
	},
	
	submit		: function(form, event) {
		event = $E(event);
		event.stop();
		event.target.blur();
		
		var data = [], inputs = $(form).getElements('ul li input'), type = inputs[0].type, options;

		// TODO: handle <select>s
		// Could be $$(input[checked=checked]
		inputs.each(function(element) {
			if(element.getProperty('checked')) {
				data.push(parseInt(element.getValue()));												 
			}
		});
		
		// Check on data
		if(data.length === 0) {
			$E(event).stop();
			alert('Επιλέξτε απάντηση(σεις) για να συνεχίσετε');
			return false;	
		}
		this._initLoader();
		
		options = {
			port	: DEBUG ? 30033 : null,
			host	: DEBUG ? '10.5.5.8' : null,
			onSuccess : function(req) {
				if(req.responseJSON) {
					// Store it
					Poll.voted = true;
					User.voteId = req.responseJSON['user_id'];	
					Cookie.set('vote_uid', User.voteId, 1000); 
				}
				Poll.fetch();
			}
		};
		
		(this.ajax || ( this.ajax = new Ajax.RPC(options))).
		send('votes.Submit', this.votespace, User.voteId, User.ip, data);
		
	},
	
	fetch		: function() {
		if(Poll.fetched) {
			this._hideLoader();
			$('poll-form').hide();
			$('poll-votes').show();
			
			return this;
		} else {
			if(!this.loader) {
				this._initLoader();	
			}
		}
	
			
		new Ajax.RPC({
			//port	: DEBUG ? 30033 : null,
			//host	: DEBUG ? '10.5.5.8' : null,
			'onSuccess' : this.render
		}).
		send('votes.GetVotespace', this.votespace, User.voteId , User.ip);		
	},
	
	render		: function(data) {
		var pixels, html = [];
		data = data.responseJSON;
		
		html.push('<ul>');
		data.votes.each(function(vote, index) {
			pixels	= parseInt(110 * (vote['total_votes'] / data['total_votes']));							 
		
			html.push('<li>');
			html.push(vote.title);
			html.push('<div class="poll-vote">');
			html.push('<div title="' + vote['total_votes'] + ' ψήφοι" style="width:' + pixels + 'px;">');
			html.push('<em style="left:'+(pixels+5) + 'px;">' + (Math.round(vote.percent * 10) / 10 )  + '%</em>');
			html.push('</div>');
			html.push('</div>');
			html.push('</li>\n');
		});
		
		html.push('</ul>');
		html.push('<div class="poll-vote">');
		
		if(!Poll.voted) {
			html.push('<span class="foo" onclick="Poll.restore()" title="Ψηφίστε">&#8249; Ψηφίστε</span>');
		}
		
		html.push('<em>' + data['total_votes'].toFormatted() + ' ψήφοι</em>');
		
		html.push('</div>');
		
		$('poll-form').hide();
		$('poll-votes').hide().setHTML(html.join('\n')).show();
		
		
		Poll._hideLoader();
		Poll.fetched = true;
	},
	
	restore : function() {
		if(this.loader) {
			this._hideLoader();
		}
		
		$('poll-form').show();
		$('poll-votes').hide();
	}
};

var Tabs = {
	active 		: null,
	container 	: null,
	catId		: null,
	
	select : function( node, container, featureUri ) {
		if( !this.active ) {
			//this.active 	= $T("li", node.parentNode)[0];
			this.active		= $(node.parentNode).getElement('.active');
			this.container 	= $("table-pop-" + this.active.id.toString().replace( /tabs-li-/gi, "") );
		}

		Node.hide( this.container );
		Node.removeClass( this.active, "active" );
		// switch
		this.active = node;
		this.container 	= $("table-pop-" + this.active.id.toString().replace( /tabs-li-/gi, "") );

		this.catId = this.container.id.toString().replace( /table-pop-/gi, "" );

		Node.show(this.container);
		Node.addClass( node, "active ");

		if(featureUri)
			$("tabs-label").innerHTML = "<a href=\""+featureUri+"?cid=" + this.catId + "\">" + node.innerHTML + "</a>";
		else
			$("tabs-label").innerHTML = "<a href=\"?cat="+this.catId+"\">"+node.innerHTML+"</a>";
	}
}

var Comparison = {
	selected	: [],
	
	initialize : function() {
		if( (this.cookie = Cookie.get('2compare')) ) {
			this.selected = this.cookie.split(',');	
		}
		
		this.button = $('results-compare-button');
		// Wrong page
		if(!this.button) {
			return this;	
		}
		this.report();
		
		//(this.inputs = $$('#results th input[type=checkbox]')).each(function(element) {
		(this.inputs = $$('#results input[type=checkbox]')).each(function(element) {
			if(Comparison.selected.contains(this.value)) {
				this.checked = true;
				this.getParent()[(this.checked ? 'add' : 'remove') + 'Class']('selected');
			} else {
				this.checked = false;
			}
			
			element.addEvent('click', function() {
				this.getParent()[(this.checked ? 'add' : 'remove') + 'Class']('selected');
				Comparison.selected[this.checked ? 'include' : 'remove'](this.value);			
				Cookie.set('2compare', Comparison.selected.join(','));
				Comparison.report();
			});
		});		
	},
	
	remove	: function(id) {
		this.selected['remove'](String(id));					
		Cookie.set('2compare', this.selected.join(','));		
		//console.log(this.selected);
		window.location = window.location.toString();
	},
	
	discard	: function() {
		Cookie.remove('2compare');	
		window.location = window.location.toString();
	},
	
	report	: function() {
		var string = 'Επιλέξτε τουλάχιστον 2 προϊόντα';
		if(this.selected.length > 1) {
			string = 'Συγκρίνετε ('+this.selected.length+') προϊόντα';
			this.button.disabled = false;
		} else {
			this.button.disabled = true;
		}
		
		
		this.button.setValue(string);
	}
};

Coupons = {     
                stepInterval : 5000,                                                                                                                                    // Timeout to stepping
                walkInterval : 2000,                                                                                                                            // Timeout to walking
                        
                initialize : function() {
                        if(window.ie6 || window.ie5) {
							PNGFix.fix($$('#coupons li img'));
						}
						
                        this.items              = $('coupons').getElements('li');

                        // Assign index for every item
                        this.items.each(function(item, index) {
                                item.index = index;
                        });     
                        
                        this.active             = $('coupons').getElement('.active');                                                   // Active item (element)
                        this.stepTimer  = this.walk.periodical(this.stepInterval, this);                                // Walking ...
                        this.fx                 = new Fx.Scroll($('coupons-content'), {
                                duration                : this.stepInterval / 4,
                                transition              : Fx.Transitions.Quad.easeInOut                                                         // http://demos111.mootools.net/Fx.Transitions
                        }).scrollTo(0, 0);

                        // Assign events
                        $$('#coupons ul').addEvents({
                                'mouseover': function(event) {
                                        this.stepTimer = $clear(this.stepTimer);
                                        if(this.walkTimer) {
                                                //this.debug('Halted Walking'); 
                                        }
                                        this.walkTimer = $clear(this.walkTimer);
                                        if(this.active === (event.target.nodeName !== 'LI' ? event.target.getParent() : event.target)) {
                                                return false;
                                        }


                                        this.select(event.target.nodeName !== 'LI' ? event.target.getParent() : event.target, true);

                                        //this.debug('Selecting :' + (event.target.nodeName !== 'LI' ? event.target.getParent() : event.target).textContent );
                                },

                                'mouseout' : function(event) {
                                        this.walkTimer = (function() {
                                                //this.debug('Re-Walking');
                                                this.stepTimer = this.walk.periodical(this.stepInterval, this);
                                        }).delay(this.walkInterval, this);
                                }
                        }, this);


                        //this.debug('Coupons initialized ...');
                        return this;
                },

                // Walk to the next item
                walk    : function() {
                        return this.select( this.items[this.active.index+1] || this.items[0] );
                },

                // Select a given item
                select   : function(item, skipScroll) {
                        if(item == this.active) {
                                return false;
                        }
                        this.fx.stop();
                        this.active.removeClass('active');
                        (this.active = item).addClass('active');

                        if(this.active.index == 0) {
                                skipScroll = true;
                        } 
						
						if(!skipScroll) {
                                        this.fx.scrollTo($('coupons-' + (this.active.index + 1)).getStyle('left').toInt(), 0);
                                } else {

                                        $('coupons-content').scrollLeft =  $('coupons-' + (this.active.index + 1)).getStyle('left').toInt();
                                }
                        

                        return this;
                },
                
                debug   : function(msg) {
                        $('debug').adopt($C('p').setHTML(msg)).scrollTop = $('debug').scrollHeight;
                        
                }
        };

var NearMe = {

        initialize      : function()    {

                if(!$('merchants-near'))
                        return;

		this.element = $('merchants-near');
		
		this.merchants  = JSON.parse(merchantsPops);
		this.locations 	= JSON.parse(nearbyLocations);

		var latLng 	= $(this.element).getProperty('rel').split(':');

		this.lat 	= parseFloat(latLng[0]);
		this.lon 	= parseFloat(latLng[1]);
		this.location  	= latLng[2];
                this.point  	= new GLatLng(this.lat, this.lon);
                this.map 	= new GMap2($('merchants-near'));
                this.bounds     = new GLatLngBounds();

		this.map.addControl(new GSmallZoomControl());
                this.map.enableScrollWheelZoom();

		this.showUser();
		this.getNearestMerchants();

                var clat = (this.bounds.getNorthEast().lat() + this.bounds.getSouthWest().lat()) /2;
                var clng = (this.bounds.getNorthEast().lng() + this.bounds.getSouthWest().lng()) /2;

                this.map.setCenter(new GLatLng(clat,clng));
		this.map.setZoom(this.map.getBoundsZoomLevel(this.bounds));
        },

	showUser 	: function() {

		var usericon  = new GIcon();

		usericon.image              = "/img/user_icon.png";
		usericon.shadow             = "http://www.google.com/mapfiles/shadow50.png";
		usericon.iconSize           = new GSize(20, 34);
		usericon.shadowSize         = new GSize(37, 34);
		usericon.iconAnchor         = new GPoint(9, 34);
		usericon.infoWindowAnchor   = new GPoint(9, 2);
		usericon.infoShadowAnchor   = new GPoint(18, 25);

		this.bounds.extend(this.point);

		var marker 	= new GMarker(this.point, { 'icon'  : usericon });
		marker.options 	= {};

		GEvent.addListener(marker, 'mouseover', function(event) {      

			this.options.window = $C('div').setStyles({
				'font-size'     : '10px',
				'position'      : 'absolute',
				'top'           : '50px',
				'padding'       : '0 5px',
				'left'          : '-150px',
				'width'         : '150px',
				'z-index'       : '9999',
				'background'    : '#fff',
				'border'        : '2px solid #BACCB1',
				'-moz-border-radius' : '5px',
				'-moz-box-shadow' : '0 0 5px #ccc'
			}).setHTML('<p style="font-size:11px;"><strong>Η τρέχουσα τοποθεσία σας</strong></p><p style="font-style:italic;">' + NearMe.location + '</p>').injectIn(NearMe.element.getParent().getParent());
		});

		GEvent.addListener(marker, 'mouseout', function() {  

			if(this.options.window)                    
				this.options.window.remove();
		 });

		this.map.addOverlay(marker);
	},

	getNearestMerchants : function() {

		var merchantIcon 	= new GIcon();

                merchantIcon.image                  = "/img/icon.png";
                merchantIcon.shadow                 = "http://www.google.com/mapfiles/shadow50.png";
                merchantIcon.iconSize               = new GSize(20, 34);
                merchantIcon.shadowSize             = new GSize(37, 34);
                merchantIcon.iconAnchor             = new GPoint(9, 34);
                merchantIcon.infoWindowAnchor       = new GPoint(9, 2);
                merchantIcon.infoShadowAnchor       = new GPoint(18, 25);

		this.locations.each(function() {

			var nearLoc 	= this[0];
			var merchant 	= NearMe.merchants[this[1]];

			var point = new GLatLng(parseFloat(nearLoc.lat), parseFloat(nearLoc.lon));

			NearMe.bounds.extend(point);

			var marker = new GMarker(point, { 'icon' : merchantIcon });

			marker.options = {
				'merchantId' 	: merchant.id,
				'addr'		: nearLoc.addr,
				'dist'		: nearLoc.dist,
				'title'		: merchant.title
			};

			GEvent.addListener(marker, 'mouseover', function(event) { 

				this.options.window = $C('div').setStyles({
					'font-size'	: '10px',
					'position'	: 'absolute',
					'top'		: '50px',
					'padding'	: '0 5px',
					'left'		: '-150px',
					'width'		: '150px',
					'z-index'	: '9999',
					'background'	: '#fff',
					'border'	: '2px solid #BACCB1',
					'-moz-border-radius' : '5px',
					'-webkit-border-radius': '5px',
					'-moz-box-shadow' : '0 0 5px #ccc',
					'-webkit-box-shadow' : '0px 0px 5px #ccc'
				}).setHTML('<p style="font-size:11px;"><strong>' + this.options.title+ '</strong></p><p style="font-style:italic;">' + this.options.addr  + ' (~' + this.options.dist + 'χλμ.)</p>').injectIn(NearMe.element.getParent().getParent());
			});

			GEvent.addListener(marker, 'mouseout', function() { 
	
				if(this.options.window)
					this.options.window.remove();	
			 });

			GEvent.addListener(marker, 'click', function() {  

				window.location = '/merchants/' + this.options.merchantId;
			 });

			NearMe.map.addOverlay(marker);
		});
	}
};

var priceOverlay, userOverlay;

Event.add( window, "DOMContentLoaded", function() {

	NearMe.initialize();

	Tip.initialize('#results tr th address', {
		className	: 'my-tip',
		followMouse : false,
		format		: function(content) {
			var merchantID;
			if(this.srcElement.nodeName === 'ADDRESS') {
				merchantID = this.srcElement.getPrevious().getPrevious().getProperty('href').match(/merchant.?\/([0-9]+)/i);
				if(merchantID) {
					merchantID = merchantID[1];
				}
				return '<h5>Κοντινότερο κατάστημα</h5><a title="Δείτε το στο χάρτη" href="/merchants/'+merchantID+'/#box-merchant-map">'+ content + '</a>';	
			} else {
				return content;	
			}
		}
	});	

	Poll.initialize;
	
	// Comparison init
	Comparison.initialize();

	if($('box-newcoupons'))
	{
		//alert("bip");
		Coupons.initialize();//.bind(Coupons);
	}
												
												
	$$('.png').each( PNGFix.fix );
	if($('form-search'))
	$("form-search").autocomplete = "off";

	if($('map'))	{
		Map.initialize();
	}
	
	priceOverlay = new Overlay($('price-overlay-node'), {
		onInit : function() { 
			$("field-overlay-price").focus();
		}
	});

	userOverlay = new Overlay($('overlay-node'), {
		onInit : function() {
			$("field-overlay-username").value = $("field-overlay-password").value = "";
			$("field-overlay-username").focus();
			if( $("field-sort") && System.browser.ie60 )
				$("field-sort").style.visibility = "hidden";
		},
		onClose : function() {
			if( $("field-sort") && System.browser.ie60 )
				$("field-sort").style.visibility = "visible";
		}
	});
	// Handle focus/blur
	var elements = $T("input").concat($T("textarea"));
	
	
	elements.each(function(element) {
		$(element).addEvent( "focus", function() {
			// IE has it defined already
			//if( isUndefined(document.activeElement) )
			if( !System.browser.ie && typeof document.activeElement == 'undefined' )
				document.activeElement = this;
			if( Menu )
				Menu.hide();
			Node.addClass( this, "focus");
		});
	});

	elements.each(function(element) {
		$(element).addEvent( "blur", function(element) {
			if( this.nodeName == "INPUT" && this.type == "text" ) {
				this.value = this.value.trim();	
			}

			if( !System.browser.ie && typeof document.activeElement == 'undefined')
				document.activeElement = null;
			Node.removeClass( this, "focus");
		});
	});

	// Focus the fU on load.
	// Only do so if the scrollTop is propper.
	var st = document.body.scrollTop || document.documentElement.scrollTop;
	var fQ = $("field-q");
	//alert( document.activeElement);

	// Cencoring
	Censor.init();

	// Setup keyhanlder 
	Event.add ( document, "keydown", function(e) {
		// F2
		if( e.keyCode == 113 ) 	{
			Node.toggle( "demo");
		}

		if( e.keyCode == Element.Event.keys['ESC']) {
			Tooltip.hide();
			Menu.hide();
			if( History.isPopulated ) {
				History.hide();
				Event.stop(e);
			}
		}
	});

	// Setup click handlers
	Event.add( document, "click", function(e) { 
		var t = Event.target(e);

		 console.log( t.parentNode.id );
		if( t.parentNode.id != "menu-allcats" && Menu.isOpen )
			Menu.hide();

		if( History.toggler && History.isOpen && History.isPopulated ) {
			var myNode = t;
			while( ( myNode = myNode.parentNode ) != null && myNode != History.toggler );
			if(  !myNode ||  myNode != History.toggler)
				History.hide();
		}

		// TODO: fix this
		if ( Zoom.current ) {
			var myNode = t;
			while( myNode && (myNode = myNode.parentNode) != null && t != Zoom.current )
				Zoom.hide();
		}

		// Tooltip
		if( Tooltip.current ) {
			if( Tooltip.current._tooltip ) {
				myNode = t;
				while( myNode != null && myNode != Tooltip.current._tooltip) { myNode = myNode.parentNode; }
				if( !myNode )
					Tooltip.hide();
			}
		}
	});

	/* I am gonna get back the AC object named as myAC and use it or not :) */
	// For further reference check out lexicon wigdet in path blogs (autoc)
	var myAjaxRPC = new Ajax.RPC();
	var options 	= {
		'className'	: "autocomplete",
		'autocomplete'  : true,
		'valueKey' 	: "q",
		'valueFormat' 	: "$1.toString().toLowerCase().camelCase()",
		//'submitForm'	: true,
		'fetch' 	: function( value ) {
			console.log(value.toString());
			return ( myAjaxRPC.send( "morpheus.GetPartialQuerySuggestions", value.toString(), 10));
		},
		'format'	: function( obj ) {
			var cnt = String(obj.n);
			if ( cnt.length > 3 )
				cnt = cnt.replace( /^(.*?)(.{3})$/, "$1.$2");
			var title = obj.q.toString().toLowerCase().camelCase().replace(/σ( |\.|$)/g, 'ς$1');
			return (  title + "<span>" + cnt + "</span>");
		},
		'events' 	: {
			//'select' : function() {
			//	this.element.form.submit();
			//},
			'close' : function() {
			},
			'loading' : function() {
				Node.toggleClass( this.element, "loading");
			},
			'halt' : function() {
				Node.removeClass( this.element, "loading");
			}
		}
	}

	new AutoComplete ( $("field-q"), options);
	if($('field-q-bottom') && !feature) {
		new AutoComplete ( $("field-q-bottom"), options);
	}
	// Focus 
	if( st <= Pos.get(fQ).y && !window._notOnFocus ) {
		try {
		$("field-q").focus();
		} catch(ex) { }
	}
})


/* 
 * toggleMore()
*/
function toggleMore(node) {
	var b = $CN("item-more", node.parentNode.parentNode)[0]; // body
	if( !b )
		b =  $CN("item-more", node.parentNode.parentNode.parentNode)[0];

	var  span = node.parentNode; // Body container (span)
	var clone;

	if( !Node.isVisible( b)  || !b.style.display) {
		b.style.display = "inline";
		node.innerHTML = "&laquo;&laquo;";
		node.title  = "λιγότερα";
		clone = span.cloneNode(true);
		Node.remove(span);
		b.appendChild(clone);
		clone.removeChild( clone.childNodes[0] ); // Remove dots
		clone.insertBefore( $CT("\xA0"), clone.childNodes[0]);
	} else {
		Node.hide( b );
		node.innerHTML = "περισσότερα &raquo;";
		clone = span.cloneNode(true);
		Node.remove(span);
		node.title  = "περισσότερα";
		b.parentNode.appendChild(clone);
		clone.insertBefore( $CT(" ... "), clone.childNodes[0]);
	}
}


/* 
 * toggleMoreCats()
 */
function toggleMoreCats(node) {
	var b = $CN("item-more", node.parentNode.parentNode)[0]; // body
	if( !b )
		b =  $CN("item-more", node.parentNode.parentNode.parentNode)[0];

	var  span = node.parentNode; // Body container (span)
	var clone;

	if( !Node.isVisible( b)  || !b.style.display) {
		b.style.display = "inline";
		node.innerHTML = " &laquo;&laquo;";
		node.title  = "λιγότερα";
		clone = span.cloneNode(true);
		Node.remove(span);
		b.appendChild(clone);
		// Nasty :)
		if(clone.children && clone.children.length > 1 )
			clone.removeChild( clone.childNodes[0] ); // Remove dots
		//} else {
		//clone.insertBefore( $CT(" "), clone.childNodes[0]);
		//}
} else {
	Node.hide( b );
	node.innerHTML = "... &raquo;";
	clone = span.cloneNode(true);
	Node.remove(span);
	node.title  = "περισσότερα";
	b.parentNode.appendChild(clone);
	clone.insertBefore( $CT(""), clone.childNodes[0]);
}
}



/* 
 * toggleMore()
*/
function toggleList( node, item ) {
	// Already working

	node = $(node);
	if( node._isSaving )
		return;

	// Not logged in
	if( !userId || !item) {
		userOverlay.open();
		return false;
	}

	node._isSaving = true;
	// TODO: 
	// Get the ajax call right
	// Set the relativity of the parent to relative
	
	if(node.getParent().nodeName === 'CODE') {
		node.parentNode.style.position = "relative";
	
		// Add loader
		node._loader 		= $C("div");
		node._loader.className	= "loader";
		
		node._loader.setStyles({
			left: node.offsetLeft,
			top: node.offsetTop		
	
		});
		node.parentNode.appendChild( node._loader);
	}
	
	// hide it
	node.setOpacity ( 1 );
	var string  		= "ΠΡΟΣΤΕΘΗΚΕ";
	var historyCountNode 	= $("list-count");
	var historyCount	= parseInt(historyCountNode.innerHTML.replace( /\D/, "") );

	var listAjax = new Ajax.RPC({
		//'host': '10.5.5.8', 'port': 30050,
		onTimeout 	: function() {alert( "Παρουσιάστηκε πρόβλημα κατά την εκτέλεση της ενέργειας. Παρακαλώ δοκιμάστε αργότερα");},
		onComplete 	: function() {
			_complete();
		}
	});
	function _complete( ) {
		var mode = listAjax.options.mode;
		historyCountNode.style.backgroundColor = "yellow";

		if( mode == 0  ) {
			node.src = node.src.replace( /add/, "remove");
			node.title = "Αφαίρεση από τη λίστα";
			historyCount ++;
		} else {
			string = "ΑΦΑΙΡΕΘΗΚΕ";
			node.title = "Προσθήκη στη λίστα";
			node.src = node.src.replace( /remove/, "add");
			historyCount --;
			historyCount = Math.max (0, historyCount);
		}

		// Kill loader
		if(node._loader) {
			Node.remove( node._loader );
		}
		node.setOpacity ( 1 );
		node._loader = null;

		node._isSaving = null; // Nullify to avoid leaks
		historyCountNode.innerHTML =  historyCount > 0 ? "("+historyCount+")" : "";
		setTimeout( function() { 	historyCountNode.style.backgroundColor = "white" ; }, 500 );
	}

	if(node.src.indexOf( "add" )  != -1 ) {
		// AddToList
		listAjax.options.mode = 0;
		listAjax.send (  "morpheus.AddToList", userLogin.toString(), parseInt(item), false);
	} else {
		// RemoveFromList
		listAjax.options.mode = 1;
		listAjax.send (  "morpheus.RemoveFromList", userLogin.toString(), parseInt(item));
	}
}

// related

var History = {
	//container : null,
	isOpen		: false,
	isOpening	: false,
	isPopulated 	: false,
	toggler 	: null,

	ajax : new Ajax.RPC ({
		ontTimeout : function() {
				alert( "Παρουσιάστηκε πρόβλημα, παρακαλώ δοκιμάστε ξανά μετά");
				History.hide();
				return;
		  },
		onSuccess : function (r) {
			// Populate the history-container
			if( r.responseJSON.faultCode  ) {
				alert( "Παρουσιάστηκε ένα πρόβλημα κατά την ανάκτηση του ιστορικού αναζητήσεων, δοκιμάστε αργότερα");
				this.isOpening = false;
				History.hide();
				return;
			}
			if( !r.responseJSON.length  ) {
				History.container.innerHTML = "";
				var l = $C("li");
				l.className = "explain";
				l.innerHTML = "'Aδειο ιστορικό";
				History.container.appendChild( l );
				return;
			}

			// Populate
			History.container.innerHTML = "";
			r.responseJSON.forEachBind( function() {
				var l = $C("li");
				// Handle special phrases
				// TODO : NOT, OR, ETC
				// FIX THIS!
			      var q = this.toString().toLowerCase().camelCase().replace(/σ( |\.|$)/g, 'ς$1');
				if(!q) {
					return false;
				}
				// Fix the final sigma
				var qTitle = q;
				qTitle = qTitle;
				if( qTitle.length > 24 )
					qTitle = qTitle.substr(0, 20) + " ..";

				l.innerHTML = "<a title=\""+ q + "\" href=\"?q=" + q + "\">" + qTitle + "</a></li>\n";
				History.container.appendChild( l );
			});

			//
			var l = $C("li");
			l.className = "explain";
			l.innerHTML = "Εμφανίζονται μόνο οι τελευταίες 20 αναζητήσεις σας";
			History.container.appendChild( l );

			if (r.responseJSON.length) {
				var l = $C("li");
				l.innerHTML = "<a title=\"Διαγραφή\" href=\"javascript:void(0)\" onclick=\"if (confirm('Διαγραφή ιστορικού;')) History.clear();\">Διαγραφή ιστορικού</a></li>\n";
				History.container.appendChild( l );
			}

			if( $("field-sort") && System.browser.ie60 )
				$("field-sort").style.visibility = "hidden";
		}
	}),
	show : function(node, event ){
		if( !node ) {
			node = $("history-toggler").parentNode;
		}

		if( !userId ) {
			alert( "Πρέπει να έχετε κάνει είσοδο στο Pathfinder για να συνεχίσετε");
			return false;
		}
		if( this.isOpen ) {
			this.hide();
			return;
		}
		this.isOpening = true;
		this.container = $("history-container");
		if (!this.isPopulated ) {
			this.populate();
			this.container.innerHTML = "<li style=\"background: url('http://c.pathfinder.gr/img/icons/loading-circle.gif') no-repeat 10px 50%;overflow: hidden; text-align: left;color: #6f6f6f;padding: 2px 0 2px 40px!important; \">ανάκτηση λίστας</li>\n";
		} else {
			if( $("field-sort") && System.browser.ie60 )
				$("field-sort").style.visibility = "hidden";
		}
		// Register toggler
		this.toggler	 = node;
		Node.addClass( node.previousSibling, "nobg");
		Node.addClass (node, "expanded");

		// hold on a sec
		this.isOpen = true;
		//this.isOpen = true;
	},

	clear : function() {
		Ajax.rpc ( "morpheus.DeleteUserQueries", userId, {
			ontTimeout : function() {
				alert( "Παρουσιάστηκε πρόβλημα, παρακαλώ δοκιμάστε ξανά μετά");
				History.hide();
				return;
			},
			onSuccess : function () { 
				var l = $C("li");
				History.container.innerHTML = "";
				l.className = "explain";
				l.innerHTML = "'Aδειο ιστορικό";
				History.container.appendChild( l );
			}
		});
	},

	populate : function() {
		this.ajax.send( "morpheus.EnumLatestUserQueries", userId, 20);
		setTimeout( function(){ this.isOpening = false;}.bind(this), 1000);
		this.isPopulated = true;
	},
	hide : function() {
		if( !this.isOpen )
			return;
		Node.removeClass( this.toggler.previousSibling, "nobg");
		Node.removeClass (this.toggler, "expanded");
		this.isOpen = false;

		if( $("field-sort") && System.browser.ie60 )
			$("field-sort").style.visibility = "visible";
	}
}

// Tooltip {}
var Tooltip = {
	current 	: null,
	instances	: [], // Gather them
	
	
	doFxFade		: !System.browser.ie,
	doFxMove		: true,
	
	useBody			: true,
	
	handlersSet		: false,
	
	_inverse		: false,
	
	pos : function(node) {
		if( !node && !(node = Tooltip.current) )
			return;
		
		var nodeWidth 	= node._tooltip.offsetWidth, nodeHeight = node._tooltip.offsetHeight, nodeLeft, nodeTop;
		var xy 			= Pos.get(node);		
		

		var offsetMove	= this.doFxMove ? 15 : 0;
		var offsetMoveInv = System.browser.safari ? 15 : 0;
		if ( System.browser.safari )
			offsetMove -= 15
		
		
		// Check limits
		var innerWidth 	= window.innerWidth
			? window.innerWidth	 + Pos.getScrollLeft()
			: document.documentElement.clientWidth 	|| document.body.clientWidth;
		var innerHeight = window.innerHeight 
			? window.innerHeight + Pos.getScrollTop()
			: document.documentElement.clientHeight	|| document.body.clientHeight;
		
		// limit check
		// skipped horizontal check for now
		if( !this.useBody )	{
			nodeTop 	= xy.y + nodeHeight > innerHeight ? - nodeHeight - 10 : 20;
			nodeLeft 	= xy.x + nodeWidth && 0 > innerWidth ? - nodeWidth - 10 : 20;		
		} else {
			nodeTop 	= xy.y - nodeHeight < Pos.getScrollTop()  ?  xy.y  - offsetMoveInv								: xy.y - nodeHeight  + offsetMove; // 15 pixels

			if( nodeTop != xy.y - nodeHeight  + offsetMove ) {
				this._inverse = true;
			}
			
			nodeLeft 	= xy.x + nodeWidth && 0 > innerWidth ? xy.x - nodeWidth/2				: xy.x - (nodeWidth/2) + (node.offsetWidth / 2);		
		}
			
			
		if( this._inverse ) {
			Node.addClass( node._tooltip , "tooltip-inverse");
		} else {
			Node.removeClass( node._tooltip, "tooltip-inverse");			
		}



		node._tooltip.style.top 	= nodeTop 	+ "px";
		node._tooltip.style.left 	= nodeLeft 	+ "px";
					
		return;
	},
	
	construct: function( node, content ) {
		var _base 		= $C("div");
		var _content 	= $C("div");
		var _closeHTML;

		// Safari needs extra care here
		if( System.browser.safari && this.useBody )
		{
			if( node.parentNode.className == "tooltip" )
				node.parentNode.style.position = "static";
		}
		
		// Init pos
		with( _base.style ) {
			position 	= "absolute";
			left 		= top = 0;
		}
	
		_base.className 	= "tooltip-window";
		_content.className 	= "tooltip-content";		
		
		
		// Add closer to content
		_closeHTML  = "<img onclick=\"Tooltip.hide()\" alt=\"κλείσιμο\" class=\"tooltip-close\" ";
		_closeHTML += "onmouseover=\"Node.addClass(this, 'hover')\" onmouseout=\"Node.removeClass(this, 'hover')\" ";
		_closeHTML += "src=\"http://c.pathfinder.gr/js/core/img/rte/close.gif\" height=\"8\" alt=\"κλείσιμο\" title=\"κλείσιμο\" width=\"8\" />\n";
		
		var _html 	= "<div class=\"tooltip-top\"></div><div class=\"tooltip-top-inverse\"></div>" + "<div class=\"tooltip-bottom\"></div><div class=\"tooltip-bottom-inverse\"></div>\n";
		
		// append html
		_base.innerHTML 		= _html;
		_content.innerHTML 		=  "<div class=\"tooltip-inner\">" + _closeHTML + content + "</div>\n";
				
		// Append
		_base.insertBefore(_content, _base.childNodes[2] );
		
		if( !this.useBody )
			node.parentNode.insertBefore(_base, node);
		else 
			document.body.appendChild(_base);

		


		// Fix pngs
		PNGFix.fix( $CN("tooltip-bottom", _base)[0]);	
		PNGFix.fix( $CN("tooltip-top", _base)[0]);
		PNGFix.fix( $CN("tooltip-bottom-inverse", _base)[0]);	
		PNGFix.fix( $CN("tooltip-top-inverse", _base)[0]);
		PNGFix.fix( $CN("tooltip-content", _base)[0]);

		
		// Pointer
		_base.content = _content;
		//this._castShadow(_base);
	
		// Assign it
		node._tooltip = _base;
		
		this.pos( node );	
	
		if( this.doFxFade ) {
			// Init opacity and fade	
			_base.setOpacity( 0 );
			_base._fxFade = new Fx.fade( _base, {
				duration: 600,
				from: 0,
				to: 1
			});
		}
		
	

	
		
		// Add to list
		Tooltip.instances.push(node);

		
		return _base;
	},
	
	show : function( key, event, offerDescr ) {
		console.log(key,event);
		
		var node 	= Event.target(event);
		if(!offerDescr)
			var content = this.tips[key] || key;
		else
			var content = "<h6>Εκπτωτικό κουπόνι</h6><p>"+offerDescr+"</p>";
		var self	= this;
	
		
		// Already on? hide it instead
		
		if( node._tooltipVisible ) {			
			Tooltip.hide();
			return;
		}
		if( Tooltip.current ) {
			Tooltip.hide();
			Tooltip.current = null;
		}
		
		// Later	
		if( node.nodeName.toLowerCase() == "img"  && !/featured/i.test(node.src) && !/trusted1/i.test(node.src) && !/trusted2/i.test(node.src) && !/auction-icon/i.test(node.src)) {
			node.src = node.src.replace( /\.gif/, "-active.gif");
		}
		
		// Set up handlers
		if( !this.handlersSet ) {	
			Event.add ( document, "keydown", function(e) {
					if( e.keyCode == Element.Event.keys['ESC'] ) {							
						if( ( node = Tooltip.current ) )
							self.hide();		
					}
				}
			);
			this.handlersSet = true;
		}
		
		// Hold the horses
		Event.stop(event);
		
		// Create tooltip
		if( !node._tooltip ) {
			this.construct( node, content );
		} else {
			Node.show(node._tooltip);
			this.pos ( node );
			
			if( this.doFxFade) {
				node._tooltip.setOpacity( 0 );
				node._tooltip._fxFade.onComplete	 = function() {node._tooltip.show();}
				node._tooltip._fxFade.toggle();
			}
		}

		if( $("field-sort") && System.browser.ie60 )
			$("field-sort").style.visibility = "hidden";

		if( this.doFxMove ) {
				node._tooltip._fxMove = new Fx.Scroll ( node._tooltip, {
						'mode': 'vertical',
						'duration': 200
				}).toBottom();
			//node._tooltip._fxMove.fx.my.start();	
		}


		node._tooltipVisible = true;
		
		

		
		setTimeout( function() {self.current = node; }, 300 );
	},

	hide : function(node) {
		if( !node && !(node = Tooltip.current))
			return
		
		// Later	
		if( node.nodeName.toLowerCase() == "img" ) 
			node.src = node.src.replace( /\-active\.gif/, ".gif");
				
		
		if( node._tooltip && this.doFxFade) {
			node._tooltip._fxFade.onComplete   = function() { node._tooltip.hide(); };
			node._tooltip._fxFade.toggle();
		} else {
			Node.hide( node._tooltip );
		}
		Tooltip.current 		= null;
		Tooltip._inverse		= false;
		node._tooltipVisible 		= false;
		if( $("field-sort") && System.browser.ie60 )
			$("field-sort").style.visibility = "visible";
	}
}

// Menu related
var Menu = {
	timerOver  	: null,
	timerEnd	: null,
	timerOut	: null,
	restoreFocus	: false,
	currentNode	: null,
	prev		: null,
	isOver		: false,
	isOpen		: false,
	intervalOver   	: 300, // MouseOver delay
	intervalOut	: 100, // MouseOut delay

	applyShield  : function() {
		$(this.currentNode).getElement('ul').shield();
		return;

		if( !System.browser.ie60  || 1)
			return;
		if( this.currentNode.shield )
			Node.show(this.currentNode.shield );
		if( !this.currentNode.shield) {
			this.currentNode.shield = $C("iframe");
			with(this.currentNode.shield) {
				frameMargin 	= 0;
				frameBorder  	= 0
			}
			this.currentNode.shield.style.position 	= "absolute";
			this.currentNode.shield.style.zIndex 	= 99;
			if( this.currentNode.id != "menu-allcats" )
				this.currentNode.shield.style.left = "-1px";
			else 
				this.currentNode.shield.style.right = "-1px";
			Node.hide(this.currentNode.shield);
			this.currentNode.appendChild( this.currentNode.shield );
		}

		// Position 
		var ul 		= $T("ul", this.currentNode)[0];
		var ulXY 	= Pos.get(ul);

		this.currentNode.shield.style.top = this.currentNode.offsetHeight + "px";
		with(this.currentNode.shield.style) {
			width 	= ul.offsetWidth  + "px";
			height =  ul.offsetHeight + "px";
			//top 	= ulXY.y + "px";
			//left 	= ulXY.x + "px";
		}
		Node.show(this.currentNode.shield);
	},

	show	: function( node, check ) {
		var prevMenuItem = null;
		if( document.activeElement == $("field-q") && !this.restoreFocus ) {
			try { document.activeElement.blur(); } catch (ex) { }
			this.restoreFocus = true;
		}
		// Hide the history
		History.hide();
		Tooltip.hide();

		if( check && ( Menu.prev != node ) ) 
			return;
		// Get the previous menu item
		// Remove bg from previous menu item

		if( node.id != "menu-allCats" && (prevMenuItem =  $(node).getPrevious()) ) 
				Node.addClass( prevMenuItem, "nobg");

		Node.addClass( node, "hover" );
		Menu.currentNode = node;
		Menu.isOver = true;
		Menu.isOpen = true;
		this.applyShield();
	},
	hide	: function( node, event ) {
		if( !node )
			node = Menu.currentNode;
		if( !node )
			return;
		var prevMenuItem;
		Node.removeClass( node, "hover" );
		if( prevMenuItem =  node.getPrevious() ) 
			Node.removeClass( prevMenuItem, "nobg");
		if( System.browser.ie60 ) {
			if( this.currentNode ) {
				if( this.currentNode.shield ) {
					try{ Node.hide( this.currentNode.shield); } catch (ex) {}
				}
			}
		}
		Menu.currentNode = null;
		Menu.isOpen = false;
	},
	over	: function(node, event) {
		event = event || window.event;
		// Track focus
		// Handle prev item - if applicable
		if( Menu.prev && ( Menu.prev != node ) )
			Menu.hide( Menu.prev);
		Menu.prev = node;
		// Remove timers
		if( Menu.timerOut)  {
			clearTimeout( Menu.timerOut);
			Menu.timerOut = null;
		}
		if( Menu.timerEnd ) {
			clearTimeout( Menu.timerEnd);
			Menu.timerEnd = null;
		}
		if( Menu.timerOver && Menu.isOver ) {
			Menu.show(node);
		} else {
			Menu.timerOver = setTimeout( Menu.show.bind( Menu, node, true), Menu.intervalOver );
		}
	},
	
	out	: function(node, event) {
		// check out: http://groups.google.com/group/comp.lang.javascript/browse_thread/thread/dc08abb05ffd0d90/5be797089178673b?lnk=st&q=mouseover+nested+elements&rnum=1#5be797089178673b

		// 3] Phase three is called the bubbling phase. The event goes back to the
		// document node, triggering all event handlers defined on the parent
		// elements for the bubbling phase. 

		// Since we have leaks here - always happening - check out to element
		var to 		= event.relatedTarget || event.toElement;
		var toParent 	= null;
		
		// FIXME:
		// this is not working ok
		try { toParent = to.parentNode } catch(ex) {}
		// Bail out
		if( toParent  ) {
			if( !toParent.parentNode )
				return;
			if( toParent.parentNode == node || toParent.parentNode.parentNode == node )
				return
		}
		// Bail out if we are on another menu item and the menu.timerover is running.
		if( toParent ) {
			if( !Node.hasClass( to.parentNode, "menu-null" ) ) {
				if( Menu.timerOver && toParent.parentNode.parentNode == $("menu"))
					return;
			}
		}
		// Restore focus
		if( this.restoreFocus ) {
			$("field-q").focus();
			this.restoreFocus = false;
		}
		Menu.hide( node );
		clearTimeout( Menu.timerEnd);
		Menu.timerEnd = null;

			
		// if( !Menu.isOver ) {
			clearTimeout ( Menu.timerOver );
			Menu.timerOver = null;	
		// }
		// FIXED: Removed the Menu.isOver statement, seems to be buggy in IE6

		Menu.timerEnd = setTimeout( function() {
			if( Menu.timerOver ) {
				clearTimeout ( Menu.timerOver );
				Menu.timerOver = null;
				Menu.isOver = false;
			}
		}, Menu.intervalOut);
	}
}
/*
 * toggleFilter()
 *
 * node 		: The link node acting as a referejnce
 * identifier	: The string identifider
*/
function toggleFilter( node, identifier ) {
	var img, span;
	var block 		= $("filter-"+identifier+"-more");

	// Sanity check
	if( !block )
		return;

	img	= node.childNodes[0];
	span	= node.childNodes[1];

	//if ( !block.isFull)
	//	block.style.height = block.style.margin = block.style.padding =  0;		// no height/margin/padding
	
	var onComplete = null;
	if( identifier == "price" ) {
		onComplete = function() {
			$("field-filter-from").focus();
		}
	}
	if (!block.fx) {
		block.fx = new Fx.Slide( block, {
			duration : 200,
			'onComplete' : onComplete
		}).hide();
	}

	// Expanding
	if( !block.isFull ) {
		block.fx.slideIn();

		span.innerHTML 	= "Λιγότερα";
		img.src 	= img.src.replace( "closed", "opened");	
		block.isFull = 1;
	} else { 
		// Collapsing
		if( block.fx.isFxing )
			block.fx.stop();
		block.fx.slideOut();
		span.innerHTML 	= "Περισσότερα";
		img.src		= img.src.replace( "opened", "closed");
		block.isFull = 0;
	}
}


/*
 * checkInput
 *
 * Check input for propper numeric value 
*/
function checkInput( field, event ) { 
	// Check: http://www.quirksmode.org/js/keys.html
	var keyCode 	= event.keyCode || event.charCode;
	var charCode 	= String.fromCharCode( keyCode ) + "";
	if( keyCode > 39 ) {
		if( !(/[0-9,\.]/.test(charCode) )  )  {
			Event.stop(event);
			return false;
		}
	}

}


var Zoom = {
	current 	: null,
	isOpen		: false,
	wins		: [],

	overWin		: false,
	
	
	timerOutInterval : 300,
	timerOut	: null,
	
	_getImg	: function( node ) {
		var cell;
		if( viewMode != "grid" ) {
			cell = node.parentNode.parentNode;
		} else {
			cell = node.parentNode;
		}
		if( !cell.nodeName == "TH" )
			return;

		var img;
		if($T("code", cell)[0])
			img 	= $T("img", cell)[1];	
		else
			img     = $T("img", cell)[0]; 

		return img;
	},
	
	
	// contruct window
	create	: function( node, width, height, merchant, url ) {
		var img 			= this._getImg(node);
		var imgSmall 		= img.src;
		var imgFull 		= img.src.toString().replace( /pathfinder.gr/, "pathfinder.gr/Full").replace(/pstatic.gr/, "pstatic.gr/Full");

		var win 			= $C("div");
		win.className 		= "zoom-container";
		win.style.width 	= width+ "px";
		win.innerHTML   	= img.title + "<span class=\"zoom-arrow\"><!-- --></span><br /><br /><div class=\"zoom-img-container\"><a target=\"pshw\" href=\""+url+"\"><img alt=\"image\" src=\""+imgSmall+"\" width=\""+width+"\" height=\""+height+"\" /><img alt=\"image\" style=\"display: none;\" src=\""+imgFull+"\" width=\""+width+"\" height=\""+height+"\" /></a><div><p>"+merchant+"</p>";

		document.body.appendChild( win );
		this.wins[node.uniqueID] = win.show();
		win.fx = new Fx.Style(win, 'opacity').set(0);
		
		//win.setOpacity( 0 );
		
		// Loader
		var imgNodeSmall 	= $T("img", win)[0];
		var imgNodeBig 		= $T("img", win)[1];

		var _prestige = function() {		
			Node.hide(imgNodeSmall);
			Node.show(imgNodeBig); 		
		}
		
		new Preloader(imgNodeBig.src, { onComplete : _prestige });
		
		var self = this;
		win.onmouseover = function() {
			if( self.timerOut ) {
				// console.log( "edw");
				clearTimeout( self.timerOut);
				self.timerOut = null;
			}
			self.overWin = true; 
		}
		win.onmouseout = function() {
			self.overWin = false;
			Zoom.out( self.current );
		}
		return win;
	},
	
	show 	: function( node, width, height, merchant, url ) {
		node = $(node);
		var exists = !!this['wins'][node.uniqueID]; // case boolean
	
		var win	= this['wins'][node.uniqueID] || this.create(node, width, height, merchant , url);
		
		if( this.timerOut != null ) {
			clearTimeout( this.timerOut );
			this.timerOut = null;
		}
		win.fx.start(1);
		//win.setOpacity( 0 );
		
		if( node != this.current ) {
			//console.log( "hiding");
			this.hide();
		}
		Node.show(win);
		this.current = node;
		this.pos( node );
	},
	
	hide	: function( node ) {
		node = node || this.current;
		if( !node )	return;
		var win = this.wins[node.uniqueID];
			
		win.fx.start(0);
		var self = this;
		this.overWin = false;
		this.current = null;
	},
	out 	: function( node ) {
		if( !this.timerOut ) {
			this.timerOut = setTimeout( this.hide.bind(this, node), this.timerOutInterval);	
		}
	},
	pos	: function( node ) {
		node = node || this.current;
		var x, y;
		if( !node )
			return;
			
		var xy = Pos.get(this._getImg(node));
		var win = this.wins[node.uniqueID];
		
		with( win.style ) {
			x = xy.x + 105;
			y = xy.y + 45 - (win.offsetHeight/2);
			left 	=  x + "px";
			top 	=  y + "px";
		}
	}
}


var Preview = {
	current 	: null,
	isOpen		: false,
	wins		: [],

	overWin		: false,
	
	
	timerOutInterval : 0,
	timerOut	: null,
	
	// contruct window
	create	: function( node ) {
		var scr				= this.data[node.id];
		var img 			= scr.img;
		var win 			= $C("div");
		win.className 		= "zoom-container";
		win.style.width 	= scr.width+ "px";
		
		win.innerHTML   	= "<span class=\"zoom-arrow\"><!-- --></span><div class=\"zoom-img-container\"><img alt=\"image\" style=\"display: none;\" src=\""+scr.url+"\" width=\""+scr.width+"\" height=\""+scr.height+"\" /></a></div><p style=\"margin-top: 10px\">"+scr.desc+"</p>";

		document.body.appendChild( win );
		this.wins[node.uniqueID] = win.show();
		//win.fx = new Fx.Style(win, 'opacity').set(0);
		
		var self = this;
		win.onmouseover = function() {
			if( self.timerOut ) {
				clearTimeout( self.timerOut);
				self.timerOut = null;
			}
			self.overWin = true; 
		}
		win.onmouseout = function() {
			self.overWin = false;
			Preview.out( self.current );
		}
		return win;
	},
	
	//show 	: function( node, data ) {
	show 	: function( node ) {
		node = $(node);
		var exists = !!this['wins'][node.uniqueID]; // case boolean
	
		var win	= this['wins'][node.uniqueID] || this.create(node);
		
		if( this.timerOut != null ) {
			clearTimeout( this.timerOut );
			this.timerOut = null;
		}
		//win.fx.start(1);
		win.show();
		if( node != this.current ) {
			this.hide();
		}
		
		// Loader
		var imgNodeBig 		= $T("img", win)[0];

		var _prestige = function() {		
			Node.show(imgNodeBig); 		
			Node.show(win);
			Preview.pos( node );
		}
		
		new Preloader(imgNodeBig.src, { onComplete : _prestige });
				
		this.current = node;
		this.isOpen = true;
	},
	
	hide	: function( node ) {
		node = node || this.current;
		if( !node )	return;
		var win = this.wins[node.uniqueID];
			
		//win.fx.start(0);
		win.hide();
		var self = this;
		this.overWin = false;
		this.isOpen = false;
		this.current = null;
	},
	toggle	: function( node )	{ 
		if(this.current && $(this.current) != node)	{
			this.out($(this.current));
			$(this.current).getParent().getParent().getParent().removeClass('hover');
			this.show(node);
			node.getParent().getParent().getParent().addClass('hover');
		}
		else if(this.isOpen)	{
			this.out(node);
			node.getParent().getParent().getParent().removeClass('hover');
		}
		else	{
			this.show(node);
			node.getParent().getParent().getParent().addClass('hover');
		}
	},
	out 	: function( node ) {
		if( !this.timerOut ) {
			this.timerOut = setTimeout( this.hide.bind(this, node), this.timerOutInterval);	
		}
	},
	pos	: function( node ) {
		node = node || this.current;
	
		var x, y;
		if( !node )
			return;
			
		var xy 	= Pos.get(node);
		var win = this.wins[node.uniqueID];
		var cellPos = Pos.get(node.getParent().getParent());
		
		with( win.style ) {
			x = cellPos.x + 340;
			y = xy.y - (win.offsetHeight/2);
			left	=  x + "px";
			top 	=  y + "px";
		}
	}
}




var Forms = {
	handleFocus : function(element) {
		if( !element._original && Node.hasClass( element, "field-pale") )
			element._original = element.value;
		else {
			element._original = "ως";
			if( element.name == "priceMin" )
				element._original = "από";
		}
		if( element.value == element._original ) {
			element.value = "";
			Node.removeClass( element, "field-pale");
		}
	},
	handleBlur : function(element) { 
		if( !element.value ) {
			element.value = element._original;
			Node.addClass( element, "field-pale");
		}
	},
	// TODO: Fix this to detect float points better
	handleSubmitPriceForm : function( form ) { 
		if( !(/[0-9,\.]/.test(form.priceMin.value ) ) )  {
			form.priceMin.value = "";
		}
		if( !(/[0-9,\.]/.test(form.priceMax.value ) ) ) {
			form.priceMax.value = "";
		}
	},
	validateLoginForm : function( form ) {
		if( form.plogin.value.length < 2 )  {
			alert( "Παρακαλώ δώστε ορθό όνομα χρήστη για να συνεχίσετε");
			form.plogin.focus();
			return false;
		}
		if( form.ppass.value.length < 2 )  {
			alert( "Παρακαλώ δώστε ορθό κωδικό για να συνεχίσετε");
			form.ppass.focus();
			return false;
		}
		// Work on the credentials
	},
	validatePriceForm : function( form ) {
		if (!parseInt(form.price.value)) {
			alert("Πρέπει να δώσετε μια έγκυρη ελάχιστη τιμή για την ειδοποίηση.");
			form.price.focus();
			return false;
		}
	}
}


/*
 * toggleFilters()
 *
 * Expand/collapse the filterings
*/
function toggleFilters() {
	var allFilters = $CN("filter-more");
	if( !allFilters )
		return false;

	allFilters.forEachBind( function() {
		var identifier = null, oc = null;
		if( oc = this.getAttribute( "onclick" ) ) {
			if( matches = oc.toString().match(/this, ?'(.*?)'/ )  ) {
				var block 		= $("filter-"+matches[1]+"-more");
				toggleFilter( this, matches[1] );
			}
		}
	});
}



// extra js
// merchan raters:
Event.add( window, "DOMContentLoaded", function() {
	if($('seed')){
		getChallenge();
	}
	
       if($('registerseed')){
                getRegisterChallenge();
        }
	var merchant_raters = new Array("overall", "price", "shipping", "delivery", "purchase", "service");
	cnt = 0;
	var _raterTimer;
	
	for( cnt  = 0; cnt < merchant_raters.length; cnt++) {
		var thisRater = $("field-hidden-" + merchant_raters[cnt]);
		var _cnt = merchant_raters[cnt];
		if ($(thisRater)) {
			var lala = new Rater ( "rater-" + merchant_raters[cnt], {
				imgOn		: cnt == 0 ? "img/stars/full-21.gif" : "img/stars/full-21.gif",
				imgOff		: "img/stars/null-21.gif",
				imgWidth	: 21,
				imgHeight	: 21,
				//loginUrl 	: $('fwd').value,
				className 	: "rater-my",
				_thisRater 	: thisRater,
				_cnt 		: _cnt,
				renderExpressions: false,
				useDefaultStoreMethod 	: false,
				onSelect 		: function() { 
					this.options._thisRater.value = this.rate
					var cell = $("rater-report-" + this.options._cnt)
					cell.innerHTML = this.options.expressions[this.rate]; // + " ("+this.rate+"/5)";
					cell.style.backgroundColor = "#FFFFDD";
					setTimeout( function() { cell.style.backgroundColor = "white"; } , 500 );
				},
				onHover			: function(rate)	{
					this.options._thisRater.value = this.rate;
					var cell = $("rater-report-" + this.options._cnt);

					if( rate > 0)	{						
						cell.innerHTML = this.options.expressions[rate]; // + " ("+this.rate+"/5)";
						cell.style.backgroundColor = "#FFFFDD";
						setTimeout( function() { cell.style.backgroundColor = "white"; } , 500 );
					}
					else
						cell.innerHTML = "<em>(επιλέξτε)</em>";
						
				},
				section 	: "shopping",
				username 	: "null",
				id 		: cnt,
				rate 	: $(thisRater).value
				}).build($(thisRater).value);
			lala.save = function(){ };
		}
	}
});

// Grab challenge code
function getChallenge() {
	var seed = $('seed').getValue();
	new Ajax.RPC({
		//host: "10.5.5.8", port: "30076",
		'onSuccess' : function(req) {
			var res = req.responseJSON;
			window.challenge = res['challenge'];
		}
	}).send('aux.GetChallengeString', seed, 0);

}

// Grab challenge code
function getRegisterChallenge() {
        var seed = $('registerseed').getValue();
        new Ajax.RPC({
                //host: "10.5.5.8", port: "30076",
                'onSuccess' : function(req) {
                        var res = req.responseJSON;
                        window.challenge = res['challenge'];
                }
		//lala
        }).send('aux.GetChallengeString', seed, 0);

}

// check merchant review form
function checkReviewForm(f) {
	
	if($('guestUserName').value.trim().length == 0)       {
		alert('Πρέπει να δώσετε ένα ψευδώνυμο.');
		$('guestUserName').focus();
		return false;
	}
	if($('guestUserName').value.trim().length < 4)       {
		alert('Το ψευδώνυμο πρέπει να αποτελείται από τουλάχιστον 4 χαρακτήρες.');
		$('guestUserName').focus();
		return false;
	}
	
	if ($('field-hidden-overall').value == 0 || $('field-hidden-price').value == 0 || $('field-hidden-shipping').value == 0 || $('field-hidden-delivery').value == 0 || $('field-hidden-purchase').value == 0 || $('field-hidden-service').value == 0) {
		alert('Πρέπει να βαθμολογήσετε το κατάστημα σε όλες τις κατηγορίες.');
		return false;
	}

	if ($('review').value.trim().length == 0) {
		alert('Πρέπει να γράψετε κάποια κριτική για αυτό το κατάστημα.');
		$('review').focus();
		return false;
	}

	
	nWords = 0;
	cnt = 0;
	wordArray = $('review').value.trim().replace(/[\s\.,!:]/g ,' ').split(' '); 
	for(i=0; i < wordArray.length; i++){
		//ignore empty words
		if(wordArray[i].length > 0)
			nWords++;
	}
	if (nWords < 10) {
	        alert('Η κριτική σας για το κατάστημα θα πρέπει να περιλαμβάνει τουλάχιστον 10 λέξεις');
		$('review').focus();
		return false;
	}

	if($('name').value.trim().length == 0)	{
		alert('Πρέπει να συμπληρώσετε το όνομά σας.');	
		$('name').focus();
		return false;
	}
	if($('surname').value.trim().length == 0)	{
		alert('Πρέπει να συμπληρώσετε το επώνυμό σας.');	
		$('surname').focus();
		return false;
	}
	if (!$('email').value.trim().length || !$('email').value.toString().isValidEmail()) {
		alert('Πρέπει να δώσετε ένα έγκυρο email');
		$('email').focus();
		return false;
	}
		
	if($('challenge').value.trim().length == 0) {
	         alert('θα πρέπει να πληκτρολογήσετε τον κωδικό ασφαλείας που φαίνεται στην εικόνα');
		$('challenge').focus();
		return false;
	}

	codeOk = ($('challenge').getValue() === window.challenge) && window.challenge;
	if(!codeOk){
		alert('θα πρέπει να πληκτρολογήσετε σωστά τον κωδικό ασφαλείας που φαίνεται στην εικόνα');
		$('challenge').focus();
		return false;
	}
		

	if($('terms').checked == false)	{
		alert('Πρέπει να συμφωνήσετε με τους όρους χρήσης του Pathfinder.');
		return false;
	}
	return true;
}

/* vote a review for is helpfull via core ajax */
function AddHelpFull(id, userId, good) {
	var cont = $('hl-'+ id);
	var ajax = new Ajax.rpc({
		onSuccess : function(req) {
			res = req.responseJSON;
			if( res && res.faultCode ) {    
				alert( res.faultString );
			}		       
			else			    
			{			       
				var tot = res['good'] + res['bad'];
				var s = '';	     
				if (res['good'])
					s = res['good'] + ' από ' + tot +' μέλη βρήκαν αυτό το σχόλιο αξιόλογο';
						
				if (res['good'] == 1 && tot == 1)
					s = "1 μέλος βρήκε το σχόλιο αξιόλογο";
					
				if (s) {
					$('hl-sum-'+id).innerHTML = s;
					$('hl-sum-'+id).style.display = 'block';
				}
				if (good)
					cont.innerHTML = "Βρήκατε αξιόλογο αυτό το σχόλιο.";
				else
					cont.innerHTML = "Δεν βρήκατε αξιόλογο αυτό το σχόλιο.";
			}
		}
	});

	cont.innerHTML = "Αποστολή επιλογής...";

	if (!id || !userId) {   
		alert('Missing some information');
		return false;
	}	       
	ajax.send( "morpheus.IsReviewHelpfull", parseInt(id), parseInt(userId), good);
}


// checks register form
function checkRegisterForm() {
	if (!$('field-company').value.trim().length) {
		alert('Πρέπει να δώσετε το όνομα της εταιρίας');
		$('field-company').focus();
		return false;
	}
	if (!$('field-contact').value.trim().length) {
		alert('Πρέπει να δώσετε το όνομα του υπευθύνου');
		$('field-contact').focus();
		return false;
	}
	if (!$('field-email').value.trim().length || !$('field-email').value.toString().isValidEmail()) {
		alert('Πρέπει να δώσετε ένα έγκυρο email');
		$('field-email').focus();
		return false;
	}
	if ($('field-phone').value.trim().length < 10) {
		alert('Πρέπει να δώσετε ένα τηλέφωνο');
		$('field-phone').focus();
		return false;
	}
	var reg = new RegExp('^[A-Za-z]+://[A-Za-z0-9-_]+\\.[A-Za-z0-9-_%&\?\/.=]+$');
	if (!reg.test($("field-url").value)) {
		alert('Πρέπει να δώσετε url καταστήματος');
		$('field-url').focus();
		return false;
	}

/*
       if($('challenge').value.trim().length == 0) {
                 alert('θα πρέπει να πληκτρολογήσετε τον κωδικό ασφαλείας που φαίνεται στην εικόνα');
                $('challenge').focus();
                return false;
        }

        codeOk = ($('challenge').getValue() === window.challenge) && window.challenge;
        if(!codeOk){
                alert('θα πρέπει να πληκτρολογήσετε σωστά τον κωδικό ασφαλείας που φαίνεται στην εικόνα');
                $('challenge').focus();
                return false;
        }
*/

	if(!Core.isHuman) {
		return false;
	}

	$('form-register').setProperty('action', '');

	return true;
}

// add to wishlist - obsolete
function addToWishList(userId, id, add, el) {
	var countNode 	= $("wishlist-count");
	var wishCount	= countNode.innerHTML.length ? parseInt(countNode.innerHTML.replace( /\D/, "") ) : 0;
	var ajax = new Ajax.RPC({
		onTimeout 	: function() {alert( "Παρουσιάστηκε πρόβλημα κατά την εκτέλεση της ενέργειας. Παρακαλώ δοκιμάστε αργότερα");	 },
		onSuccess 	: function(req) {
			res = req.responseJSON;
			if( res && res.faultCode ) {    
				alert( res.faultString );
			}
			else
			{
				if (wishlist)
					wishCount++;
				else
					wishCount--
				countNode.innerHTML =  wishCount > 0 ? "("+wishCount+")" : "";
				setTimeout( function() { 	countNode.style.backgroundColor = "white" ; }, 500 );
			}
		}
	});

	if (el._add)
	{
		wishlist = el._add == 1 ? false : true;
	}
	else
		wishlist = !add;
	el._add = wishlist ? 1 : 2;

	countNode.style.backgroundColor = "yellow";
	ajax.send (  "morpheus.ToggleWishList", userId, parseInt(id), wishlist);
}

// add alert after getting min price
function addAlert(node) {
	if( node._isSaving )
		return;

	priceOverlay.open();
	return false;
}


function handleCount (element, limit, fn) {
	var l = element.value.length;
	if( l > limit ) {
		element.value = element.value.substr(0,limit);
	}
	fn( element.value.length, limit );
};

function renderCount( count, limit ) {
	this.innerHTML = limit - count;
};

function checkAlertEmail(f) {
	if (f.email.value.length && !f.email.value.isValidEmail()) {
		alert('Παρακαλούμε δώστε ένα έγκυρο email');
		f.email.focus();
		return false;
	}
	return true;
}




// Cencoring
var Censor = {
	instances	: [],
	warning		: null,
	
	init		: function() {
		var censored;
		if( (  censored = $CN("censored") ) ) {
			censored.forEach( function( item )  {
				
				var img;
				if($T("code", item)[0])
					img       = $T("img", item)[1];
				else
					img       = $T("img", item)[0];

				//var img 	= $T("img", item)[1];
				
				// img, img.src, container
				var imgObj =  [ img, img.src, item ];
				Censor.instances.push( imgObj );
				
				img.src 	= "http://static.pathfinder.gr/Shopping/img/censored-img.png";
				img.width 	= img.height = 90;
				img.style.visibility = "visible";
			});
			
			if( !censored.length )
				return;
			
			
			// Set message
			this.warning = $C("p");
			this.warning .className = "warning";
			this.warning.innerHTML = "Σε αυτή την αναζήτηση βρέθηκαν πρϊόντα οι εικόνες των οποίων πιθανόν είναι να άσεμνες.<br />Για να εμφανιστούν οι εικόνες και να μην δείτε ξανά αυτό το μήνυμα κάντε <span onclick=\"Censor.set()\">κλικ εδώ</span>.";
			$("main").appendChild(this.warning);
			
		}	
		
	},
	
	set			: function() {
		if( this.warning )  {
			Node.hide(this.warning);
			Node.remove(this.warning);
			this.warning = null;
		}
		Cookie.set( "skip_censor_check", 1, 360 );
		this.restore();
	},
	
	restore		: function() {
		if( !this.instances.length )
			return;
		this.instances.forEach ( function( item) {
				item[0].src  = item[1];							  
				Node.removeClass( item[2], "censored" );
		});
	
	}
}

var Results = new Class({
	initialize 	: function() {
		// Fixed a weird bug with IE8
		if(!this.done && window.ie8) {
			this.initialize.delay(2500, this);
			this.done = true;
			return this;
		}
		this.element = $C('div').
		setStyles({
			'padding' : '8px',
			'border'  : '3px solid #ccc',
			'position': 'absolute',
			'background' : '#fff',
			'color' : '#999',
			'text-align' : 'left',
			'z-index': '50',
			'width'	: '400px',
			'line-height'	: '1.5em',
			'white-space': 'normal'
		}).
		hide().
		injectIn();

		this.fx = this.element.show().effect('opacity', {'duration': 200}).set(0);

		document.addEvents({
			'click'		: function(event) {
				var current = Results.current;
				if (current && current.isOpen && !current.element.contains(event.target, true) && !current.snapTo.contains(event.target, true))
					current.close();
			},
			'keydown'	: function(event) {
				var current = Results.current;
				if (current && event.key == 'esc')
					current.close();
			}
		});
	},
	showBrands 	: function(el) {
		this.snapTo = $(el);
		var coords = this.snapTo.getCoordinates();

		this.element.setStyles({
			'left'	: coords.left + coords.width + 10,
			'top'	: coords.top				
		});
		if (this.brands.length) {
			var s = '', i=0;
			this.brands.each(function(brand) {
				s += "<a href=\"/"+ query +"&amp;brand="+ brand.name +"\">"+ brand.name +"</a> ("+ brand.total +")";
				if (i+1 < this.brands.length)
					s += ',';
				s += ' ';
				i++;
			}, this);

			this.element.setHTML(s);
			this.fx.start(1);

			this.constructor.current = this;
			this.isOpen = true;
		}
		return false;
	},
	showMerchants 	: function(el) {
		this.snapTo = $(el);
		var coords = this.snapTo.getCoordinates();

		this.element.setStyles({
			'left'	: coords.left + coords.width + 10,
			'top'	: coords.top				
		});
		if (this.merchants.length) {
			var s = '', i=0;
			this.merchants.each(function(merchant) {
				s += "<a href=\"/"+ query +"&amp;merchant="+ merchant.id +"\">"+ merchant.name +"</a> ("+ merchant.total +")";
				if (i+1 < this.merchants.length)
					s += ',';
				s += ' ';
				i++;
			}, this);

			this.element.setHTML(s);
			this.fx.start(1);
			this.constructor.current = this;
			this.isOpen = true;
		}
		return false;
	},
	close 	: function(){
		this.fx.start(0);
		this.isOpen = false;
		return false;
	}
});
Results.implement( new Options, new Events );

function popImg( img, width, height ) {
	var top = screen.height/2 - height/2 - 80, left = screen.width/2 - width/2;
	
	if ((!window.popup)  || (window.popup && window.popup.closed) )
		window.popup = window.open( "", "popup", "width=" + width  + ", height="+(height + 30) + ", left=" + left + ", top="+top);
	else {
		window.popup.resizeTo( width  , (height + 80) );
		window.popup.focus();
	}
		
	doc = window.popup.document;
	var code = "<html>";
	code += "<head><title>" + img.title + "</title>";
	code += "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-7\" />\n";
	code += "<style type=\"text/css\">";
	code += "body {margin:0; font: normal 13px arial, serif; text-align: center; background: #eee;}\nimg { margin-bottom: 5px;}\n";
	code += "</style>\n";
	code += "</head><body>\n";
	code += "<img height=\""+height+"\" width=\""+width+"\" border=\"0\" alt=\""+img.title+"\" title=\""+img.title+"\" src=\""+img.href+"\" /><br /><a href=\"#\" onclick=\"self.close();\">[x] κλείσιμο παραθύρου</a>\n";
	code += "</body></html>";
	
	doc.write( code);
	doc.close();
}

// GeoPicker Related
GeoPicker.onSave = function() {
	console.log(1);
	alert('Η επιλογή σας αποθηκεύτηκε. Η σελίδα θα ξαναφορτώσει για να εμφανιστούν τα νέα δεδομένα.');
	(function() {
		if(window.safari) {
			window.location.href = window.location.href;
		} else {
			location.reload(false);
		}
	}).delay(100);
}

