_dev = (location.host.indexOf('.dev') !== -1 ? true : false);

String.prototype.toEng = function() {
	
	var st = this, re;
	var ar = Array(
		new Array ("ef","ευ"),
		new Array ("ps","ψ"),
		new Array ("is($| |\\.)","ης$1"),
		new Array ("a","[α|ά]"),
		new Array ("v","β"),
		new Array ("g","γ"),
		new Array ("th","δ"),		// th instead of d
		new Array ("e","[ε|έ]"),
		new Array ("th","θ"),
		new Array ("th","Θ"),
		new Array ("i","[ι|ί]"),
		new Array ("i","[η|ή|χ]"), // i not eta
		new Array ("k","κ"),
		new Array ("l","λ"),
		new Array ("m","μ"),
		new Array ("z","ζ"),
		new Array ("n","ν"),
		new Array ("o","[ο|ό]"),
		new Array ("p","π"),
		new Array ("r","ρ"),
		new Array ("s($| |\\.|,)","ς$1"),
		new Array ("s","(σ|ς)"),
		new Array ("t","τ"),
		new Array ("y","[υ|ύ]"),
		new Array ("x","[ξ|χ]"),
		new Array ("f","φ"),
		new Array ("ps","ψ"),
		new Array ("ch","χ"),
		new Array ("x","ξ"),
		new Array ("w","[ω|ώ]")
	);
	
	for (var i = 0 ; (thisI = ar[i]) ; i ++) {
		re = new RegExp (thisI[1],"ig"),
		st = st.replace(re,thisI[0]);
	}
	
	// Some more
	st = st.replace(/i( |$)/gi, 'e$1', st); // e.g dimiti to dimitre 
	st = st.replace(/i( |$)/gi, 'e$1', st); // e.g dimiti to dimitre 

	return st;
};

Number.prototype.format = function(format) {

  var hasComma = -1 < format.indexOf(','),
    psplit = format.split('.'),
    that = this; 

  // compute precision
  if (1 < psplit.length) {
    // fix number precision
    that = that.toFixed(psplit[1].length);
  }
  // error: too many periods
  else if (2 < psplit.length) {
    throw('NumberFormatException: invalid format, formats should have no more than 1 period: ' + format);
  }
  // remove precision
  else {
    that = that.toFixed(0);
  } 

  // get the string now that precision is correct
  var fnum = that.toString(); 

  // format has comma, then compute commas
  if (hasComma) {
    // remove precision for computation
    psplit = fnum.split('.'); 

    var cnum = psplit[0],
      parr = [],
      j = cnum.length,
      m = Math.floor(j / 3),
      n = cnum.length % 3 || 3; // n cannot be ZERO or causes infinite loop 

    // break the number into chunks of 3 digits; first chunk may be less than 3
    for (var i = 0; i < j; i += n) {
      if (i != 0) {n = 3;}
      parr[parr.length] = cnum.substr(i, n);
      m -= 1;
    } 

    // put chunks back together, separated by comma
    fnum = parr.join('.'); 

    // add the precision back in
    if (psplit[1]) {fnum += '<sup>' + psplit[1] + '&euro;</sup>';}
  } 

  // replace the number portion of the format with fnum
  return format.replace(/[\d,?\.?]+/, fnum);
};

// Handle google_ads requests
function google_ad_request_done(google_ads) {
    var s = '';

    // No ads
    if(!google_ads || google_ads.length === 0) {
    	//console.warn('No candidate google ads to display. Bailing out');
        return;
    }

    if (google_ads[0].type === 'flash') {
        s += '<a href=\"' +
        google_info.feedback_url + '\" style="color:000000">Διαφημίσεις Google</a><br>' + 
        '<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"' +
        ' codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=6,0,0,0" WIDTH="' + 
        google_ad.image_width + '" HEIGHT="' + 
        google_ad.image_height + '"> <PARAM NAME="movie" VALUE="' + 
        google_ad.image_url + '">' + 
        '<PARAM NAME="quality" VALUE="high">' + 
        '<PARAM NAME="AllowScriptAccess" VALUE="never">' + 
        '<EMBED src="' + 
        google_ad.image_url + '" WIDTH="' + 
        google_ad.image_width + '" HEIGHT="' + 
        google_ad.image_height + 
        '" TYPE="application/x-shockwave-flash"' + 
        ' AllowScriptAccess="never" ' + 
        ' PLUGINSPAGE="http://www.macromedia.com/go/getflashplayer"></EMBED></OBJECT>';

    } else if (google_ads[0].type == "image") {    
        s += '<a href=\"' +
        google_info.feedback_url    + '\" style="color:000000">Διαφημίσεις Google</a><br> <a href="' + 
        google_ads[0].url           + '" target="_top" title="μετάβαση στη διεύθυνση ' + 
        google_ads[0].visible_url   + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'μετάβαση στη διεύθυνση ' +
        google_ads[0].visible_url   + '\';return true"><img border="0" src="' + 
        google_ads[0].image_url     + '"width="' + 
        google_ads[0].image_width   + '"height="' + 
        google_ads[0].image_height  + '"></a>';    

    } else if (google_ads[0].type === 'html') {
        s += google_ads[0].snippet;

    } else {
        s += '<fieldset>';
        s += '<legend><a target="_blank" href=\"' + google_info.feedback_url + '\">Προβεβλημένες καταχωρίσεις</a></legend>';
    
        s+= '<ul>';

        for(i = 0; i < google_ads.length; ++i) {
            s += '<li>';
            s += '<a target="_blank" href="' + 
            google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'μετάβαση στη διεύθυνση ' +
            google_ads[i].visible_url + '\';return true">' + google_ads[i].line1 + '</a>';
            
            s += '<p>' + google_ads[i].line2 + ' ' + google_ads[i].line3 + '</p>';

            //below the color was F8382F
            s += '<em><a target="_blank" href="' + google_ads[i].url + '" onmouseout="window.status=\'\'" onmouseover="window.status=\'μετάβαση στη διεύθυνση ' + google_ads[i].visible_url + '\';return true">' + google_ads[i].visible_url + '</a></em>';
            s += '</li>';
        }

        s+= '</ul>';
        s+= '</fieldset>'
    }

    var div = document.createElement('div');
    div.className = 'gads';
    div.innerHTML = s;

    document.getElementById(window['google_ad_id'] || 'google-ads').parentNode.
    insertBefore(div, document.getElementById('google-ads'));
}



Feedback = {

	open		: function() {
		
		!this.overlay && this.build();
		
		this.overlay.open();
		
		return this;
	},
	
	build		: function() {
		
		var html = [];
		
		html.push('<div class="overlay-inner feedback">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Η άποψή σου για το BestPrice<span class="close" onclick="Feedback.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body clr">');
		html.push('<h5>1. Το email σου</h5>');
		html.push('<input style="margin: 10px 0; width: 565px; padding: 5px;" type="email" id="feedback-email" class="field" name="email" value="" placeholder="Πληκτρολόγησε το email ώστε να επικοινωνήσουμε μαζί σου σχετικά με τις παρατηρήσεις σου">');
		html.push('<h5>2. Οι παρατηρήσεις σου</h5>');
		html.push('<textarea class="field" style="width: 99%; height: 10em;" placeholder="Η άποψή σου για το BestPrice"></textarea>');
		html.push('<p style="margin-top: 20px;"><button class="button" onclick="Feedback.send()">Αποστολή</button> ή <a href="javascript:void(0);" onclick="Feedback.overlay.close();">κλείσιμο</a></p>');		
		html.push('</div>');
		html.push('</div>');		
		
		this.overlay 	= new Overlay(html.join(''), {
			'onOpen'	: function() {

				this.element.getElement('textarea').setValue('').focus();
				this.element.addClass('overlay-normal');
			},
			'beforeClose': function() {

				this.element.removeClass('overlay-normal');
			}
		});
	},
	
	send : function() {

		var feedback = this.overlay.element.getElement('textarea').value.trim(), self = this;

		if(!feedback) {
			
			alert('Δώσε κείμενο για να συνεχίσεις.');
			this.overlay.element.getElement('textarea').focus();

			return false;
		}

		var parameters = {
			'action' 	: 'submitFeedback',
			'isAjax'	: true,
			'feedback'	: feedback.replace('Η άποψή σου για το BestPrice', '').trim(),
			'email'		: this.overlay.element.getElement('input').getValue()
		};
	
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				if(parseInt(response.res.faultCode) > 0)
					alert('Σφάλμα: ' + response.res.faultString);
				else {
					
					alert('Ευχαριστούμε για το ενδιαφέρον και την βοήθεια!');
					self.overlay.close();
				}
			},
		
			'parameters' : parameters
		
		}).send();
	}
}

var SearchBox = {

	initialize : function() {
		
		if(!$('search-box'))
			return;
				
		// if we have focused to another element
		// expect for search field, dont focus in search
		// when you hit tab
		this.isFocusedToElement = false;

		// Attach search-box-clear
		if(!window.ios) {
			this.clearer = $C('span', {
				'id' 	: 'search-box-clear',
				'title'	: 'Καθαρισμός πεδίου αναζήτησης'
			}).
			hide().
			addEvents({
				'click'			: function() {
					$('search-box').value = '';
					SearchBox.disableClearing();
					$('search-box').focus();
				},

				'mouseover'		: function() {
					this.setOpacity(.8);
				},

				'mouseout'		: function() {
					this.setOpacity(.55);
				}
			}).
			injectIn( $('search-box').getParent() );
			this.clearingFX = $('search-box-clear').effect('opacity',{
				duration	: 200,
				onComplete 	: function() {
					if(this.now === 0) {
						this.element.hide();
					}
				}
			}).set(0);
			if( $('search-box').value ) {
				this.clearingFX.setOptions({
					duration: 1500
				});
				this.enableClearing();

				this.clearingFX.setOptions({
					duration: 200
				});
			}
		}
						
		$('search-form').getElement('.search-wrapper').addEvent('click', function() { $('search-box').focus(); });

		$('search-form').addEvent('submit', function(event) {
			if($('search-box').getValue() == "" || $('search-box').getValue() == $('search-box').getProperty('placeholder')) {
				
				$('search-box').focus();
				event.preventDefault();
			}
		});

		$$('input').addEvent('focus', function() { 
		
			if(this.id != 'search-box')
				SearchBox.isFocusedToElement = true;
		});

		window.addEvent('keydown', function(event) {

			if(event.meta || event.ctrl)
				return;

			if(event.code == 9) {

				if($('cart-container'))
					return;

				if($$('.overlay-inner').length > 0 && !$$('.overlay-inner')[0].isHidden())
					return;
					
				if(SearchBox.isFocusedToElement || $(document).documentElement.hasClass('focused'))
					return;

				$('search-box').focus();
				
				event.preventDefault();
			}
		});

		if($('page-home'))
			$('search-box').focus();
		
		$('search-box').addEvent('keydown', function(event) {	
			if( (event.key === 'return' && this.value) && (event.meta || event.ctrl)   ) {
				// Open in new target
				this.form.target = '_blank';
				this.form.submit();
				
				// Restore back to previous setting
				(function() {
					this.form.target = '_top';
				}).delay(100, this);
			}
		});

		$('search-box').addEvent('keyup', function(event) {
			if(this.value.length)	{
				SearchBox.enableClearing();
			} else {
				SearchBox.disableClearing();
			}

			if(event.meta || event.ctrl)
					return;
			
			/*
			if(this.getValue() != "")
				$(document).documentElement.addClass('focused'); 
			else
				$(document).documentElement.removeClass('focused');
			*/
			
			if(event.code == 27)
				$(this).blur();
		});
		
		$('search-box').addEvent('blur', function() { $(document).documentElement.removeClass('focused'); });
			
		var acHeader = '';
		
		if($('category-search')) {
			acHeader = '<a href="javascript:void(0);" ';
			acHeader += 'id="overlay-category-search" class="' + ( CategorySearch.checked ? 'checked' : '') + '" ';
			acHeader += 'onmousedown="SearchBox.ac.options.checkClose = function() { return false; }; CategorySearch.toggleActive(); if(CategorySearch.checked) { $(\'search-form\').submit(); }" ';
			acHeader += 'onmouseout="SearchBox.ac.options.checkClose = null;">';
			acHeader += $('category-search').innerHTML;
			acHeader += '</a>';

		}

		this.ac = new AutoComplete('search-box', {
			
			'popupWidth'		: 674,
			'completeOnSelect' 	: false,
			'highlightFirst'	: false,
			'autocomplete'		: false,
			'openOnFocus'		: false,
			'submitForm' 		: true,
			'minLength'			: 1,
			'maxResults'		: 8,
			'header'			: acHeader,
			'footer'			: '',
			'valueKey'			: 't',
			'offsets'			: {
				'top' 		: window.ie8 ? 8 : 9,
				'left'  	: window.ie7 ? -7 : -13,
				'right'		: window.gecko ? 5 : (window.ie8 ? 16 : 10)
			},	
			'placeholder'		: true, // will useParent
			
			'valueFormat'			: function(result) {
				if(result['t'] ){ 
					return result['t'];
				} else {
					var trail 	= result['trail'];
					var t 		= [];
					var last 	= trail.pop();
					result['last'] = last;
					
					trail.each(function(item, index) {
						t.push(item.t);
					});		
					result['scope'] = t.join(' &rarr; ');
					
					result['t'] = last ? last['t'] : '';
					return result['t'];
				}
			},		
			
			'queryFormat'		: function(q) { return q.replace(/ +/gi, ' '); },
			
			'onSelect'			: function(item) { 
		
				if(item.s == "b")
					window.location.href = '/search?q=' + item.t;
				else if(item.s == "c")
					window.location.href = '/cat/' + item.last.id + '/' + SearchBox.urlizeSlug(item.last.r);
				else if(item.s == "m")
					window.location.href = '/m/' + item.id + '/' + SearchBox.urlizeSlug(item.t);
				else
					window.location.href = '/item/' + item.path;
			},	
			
			'format'			: function(result, q, resultValue, index) {
		
				if( (index !== 0 && this.prev_s !== result.s) || (index === 0 && $('category-search')))
					result.element.style.borderTop = '1px solid #ddd';
			
				SearchBox.acDiv = SearchBox.acDiv || $C('div').injectIn(document.body).hide();
				SearchBox.acDiv.setHTML(result.t);
				
				var vowels = [ 
					'ά|α',
					'ί|ι',
					'ή|η',
					'ύ|υ',
					'ό|ο',
					'ώ|ω',
					'έ|ε'
				], hash =  {
					'b' : 'Κατασκευαστής',
					'c' : 'Κατηγορία',
					'p' : ''
				}, _q = q.toLowerCase(), fullname;
				
				vowels.each(function(v) {
					_q = _q.replace( new RegExp( '(' + v + ')', 'gi' ) , '[' + v.replace(/\|/gi, '') + ']' );
				});

				var html = [], reg = new RegExp('(^| )(' + _q.replace(/ /g, '|') + ')', 'gi');

				var title = (SearchBox.acDiv.innerText ? SearchBox.acDiv.innerText : (SearchBox.acDiv.textContent ? SearchBox.acDiv.textContent : result.t));
				
				if(title.length > 100)
					title = title.slice(0, 97) + ' ...';

				var img = '';
				
				if(result.s === 'p') {
					
					if(result.i)
						img = '<span class="img"><img width="30" height="30" src="http://x.pstatic.gr/bp/' + result['i']['p'] + '.jpg" /></span> ';
					else
						img = '<span class="img"><img width="30" height="30" src="http://x.pstatic.gr/so/n/BestPrice/img/no-image.png"/></span>';	
				}
				
				if(result.s == 'p')
					result.element.addClass('img');

				if( result.trail && result.trail[1] && result.trail[1].id === 894 && result.trail[3])
					title  += ' ['+result.trail[3]['t']+']';
	
		
				if( result.trail ) {
					
					var trail =  result.trail[result.trail.length - 1] ? result.trail[result.trail.length - 1].t : '';
					
					if( trail && trail.length > 25 )
						trail = trail.slice(0, 22) + '...';
				}
				
				if(result.trail && result.trail[result.trail.length - 1] && result.trail[result.trail.length - 1].t != '')
					html.push('<span>' + (result.trail[0].id == 609 ? '<em>Book</em>' : '') + trail + '</span>');
				else if(result.scope || hash[result.s])
					html.push('<span>' +  (result.scope || hash[result.s]) + '</span>');
				else if(result.s == 'm')
					html.push('<span>Κατάστημα</span>');
				else if(result.s == 'b')
					html.push('<span>Brand</span>');

				html.push( img + '<em>' + title.replace(reg, '$1<strong>$2</strong>') + '</em>');
				
				this.prev_trail = trail;
				this.prev_s = result.s;
				this.prev_q = q;

				return html.join('');
			},

			'fetch' : function(q) {
				
				this.prev_s 	= null;
				this.prev_trail = null;
				
				return new XHR.RPC({
					
					'host' 		: (window.location.host.indexOf('dev') !== -1 ? '10.5.5.8' 	: '10.5.5.13'),
					'port' 		: (window.location.host.indexOf('dev') !== -1 ? 30076		: 30032),
					'charset' 	: 'iso-8859-7'
					
				}).send('bestprice.PrefixSearch', 'pa9852kf2089akqsws', q, this.options.maxResults);
			}
		});
	},
	
	urlizeSlug : function(originalSlug) {
		
		if(!originalSlug || originalSlug == '')
			return '';
		
		var slug = '';
		
		slug = originalSlug.replace(/&/g, '-');
		slug = slug.replace(/ /g, '-');
	    slug = slug.replace(/:/g, '-');
		slug = slug.toEng();
		slug = slug.toLowerCase();
		slug = slug.replace(/_/g, '-');
		slug = slug.replace(/[^a-z0-9]/i, '-');
		slug = slug.replace(/ /g, '-');
		slug = slug.replace(/{(-)\1+}/g, '-'); 
		
		return slug;
	},

	enableClearing 		: function() {
		if(this.clearingEnabled || !this.clearer) {
			return this;
		}

		this.clearingEnabled = true;
		$('search-box-clear').show();	
		this.clearingFX.start(.55);
		return this;
	},

	disableClearing 	: function() {
		if(this.clearingEnabled === false || !this.clearer) {
			return this;
		}
		this.clearingFX.start(0);
		this.clearingEnabled = false;
	}
};

var Product = {
	
	initialize : function() { this.tabs.initialize(); },
	
	'tabs' : {

		'names'			: [],
		'changeHash'	: true,
		'prevHash'		: '',

		initialize : function() {
		
			if(!$('item-sections'))
				return;
				
			this.fx = new Fx.Scroll();

			// Gather the tabs
			this.tabs = $('item-sections').getElements('li');
			
			// Gather the tab names & attach event handlers
			this.tabs.each(function() {
			
				var tabname = $(this).getProperty('data-tab');

				$(this).addEvent('click', function(event) { Product.tabs.select(tabname, true, event); });
		
				Product.tabs.names.push(tabname);
			});
			
			if(window.ie && $('page-item') && $('knob'))
				$('knob').remove();
			
			// Silly fixes for Mozilla
			if(window.moz && $('knob')) {
				
				if($('page-user'))
					$('knob').setStyle('top', '39px');
				else
					$('knob').setStyle('top', '17px');
					
			} else if(window.ios && $('knob')) {
		
				if($('page-user'))
					$('knob').setStyle('top', '40px');
				else	
					$('knob').setStyle('top', '15px');
			}
			
			if($('books-carousel')) {
				
				this.changeHash = false;
				return;
			}
			
			if($('knob') && $('page-user') && $('general').getElement('.card-container'))
				$('knob').setStyle('color', '#fff');
				
			// Read the hash, if hash is one of the tabs, switch to this tab
			this.readHashAndSwitch();
			
			// If browser supports onhashchange event then by all means
			// use it (otherwise fallback to the usual periodical crap)!
			if("onhashchange" in window)
				window.onhashchange = this.readHashAndSwitch.bind(this);
			else
				this.readHashAndSwitch.periodical(100, this);
		},
		
		readHashAndSwitch : function(event) {

			if(window.location.hash != '') {
			
				var hash = window.location.hash.split(/#/)[(window.ie && !window.ie9 ? 0 : 1)];
				
				this.prevHash = (hash.indexOf('item') == -1 ? hash : hash.split(/-/)[1]);

				if($('page-item')) {

					if(hash.indexOf('item') == -1) {

						hash = 'item-' + hash;

						window.location.hash = '#' +hash;
						return;
					}

					var hashChunks = hash.split(/-/);

					hash = hashChunks[1];

					// If hash contains review id, then scroll to this review (and maintain the hash)
					if(hash == 'reviews' && parseInt(hashChunks[2]) > 0) { 
							
						var reviewElement = $('.reviews-list').getElement('li[data-review="' + parseInt(hashChunks[2]) + '"]');
						var self = this;

						if(reviewElement) {

							(function() { 

								document.body.scrollTop = document.documentElement.scrollTop = reviewElement.getPosition().y - 150;

								(function() { new Fx.Style(reviewElement, 'backgroundColor').start('#f0f0f0', '#ffffff'); }).delay(100);

								location.hash = '#item-' + hash + '-' + parseInt(hashChunks[2]);

							}).delay(0);
						}
					}	
				}

				if(this.names.indexOf(hash) > -1)
					this.select(hash, false);					
					
			} else {

				if(this.prevHash == this.names[0])
					history.back();
				else
					this.select(this.names[0], false);
			}
		},
		
		select : function(tabname, mouseUsed, event) {

			if(event && event.stop)
				event.stop();

			if(!$('item-sections'))
				return;

			var tabIndex = 0;
			
			if(!this.tabs)
				return false;
			
			this.tabs.each(function(element, index) { 
				
				if(this.getProperty('data-tab') == tabname) {
					
					tabIndex = index;
					return;
				}
				
				this.removeClass('active'); 	
			});
			
			var activeTab = $('item-sections').getElement('li[data-tab="' + tabname + '"]');

			if(activeTab.hasClass('active'))
				return;
			
			activeTab.addClass('active');
					
			$('content').getElements('div[data-box]').hide();			
			$('content').getElement('div[data-box="' + tabname + '"]').show();

			if(this.changeHash)
				window.location.hash = '#' + ($('page-item') ? 'item-' : '') + tabname;

			ScrollItem.element && ScrollItem.element.removeClass('fixed');

			// Scroll to item-properties instead			
			if(!$('page-item') && this.changeHash)
				document.body.scrollTop = document.documentElement.scrollTop = 0;

			if($('knob')) {
				
				var newX = (tabIndex * ($('.item-properties') ? 184 : 159)) + 'px';
			
				$('knob').setStyles({
					'-webkit-transform' : 'translate3d(' + newX + ', 0, 0)',
					'-moz-transform' 	: 'translate(' + newX + ', 0)',
					'msTransform' 		: 'translate(' + newX + ', 0)'
				});

				if($('page-user') && (tabname == 'mreviews' || tabname == 'reviews' || (tabname == 'general' && $('general').getElement('.card-container'))))
					$('knob').setStyle('color', '#fff');
				else if(tabname == 'havelist')
					$('knob').setStyle('color', ($('havelist').getElement('.pale') ? '#f7f7f7' : '#d6d6d6'));
				else if($('page-item') && $('page-item').hasClass('fixed'))
					$('knob').setStyle('color', '#ddd');
				else
					$('knob').setStyle('color', '#f2f2f2');
			}
		
			if(tabname == 'nearby' && !Nearby.loaded)
				Nearby.getStores();
		}
	}
}

var Filters = {
	
	initialize : function() {
		
		if(!$('filters'))
			return;
			
		$('filters').getElements('dt').addEvent('click', function() {
			
			var type = $(this).getProperty('data-filter');
			
			Filters.toggle(type, this);
		});
	},
	
	toggle : function(type, header) {
		
		$('filters').getElements('dd.price').each(function() { this.toggle(); });
		
		$(header).getElement('small').setHTML(($(header).hasClass('collapsed') ? "&#x25bc;" : "&#x25b6;"));
		$(header).toggleClass('collapsed');
		
	}
}

var LoginRegisterBox = {
	
	initialize : function() {
		
		if($$('.login').length == 0 && $$('.register').length == 0)
			return;
			
        this.overlay = new Overlay('', {
			'duration'	: 400,
			'className'	: 'overlay',
			'onOpen'	: function() {

				this.element.addClass('overlay-normal');
			},
			'beforeClose': function() {

				this.element.removeClass('overlay-normal');
			}
        });
		
		$$('.login').addEvent('click', function() { LoginRegisterBox.loginRender(); });
		$$('.register').addEvent('click', function() { LoginRegisterBox.registerRender(); });
		
		var hash = window.location.hash.split(/#/)[(window.ie && !window.ie9 ? 0 : 1)];
		
		if(hash == 'join')
			this.registerRender();
	},
	
	loginRender : function(fwd, youNeedToLogin) {
		
		this.registerRender(fwd, youNeedToLogin);
		return;
		
		var fwd = (typeof fwd != 'undefined' && fwd != '' ? fwd : '');
		
		this.overlay = this.overlay || new Overlay('', {
			
			'duration'	: 400,
			'className'	: 'overlay',
			'onOpen'	: function() {

				this.element.addClass('overlay-normal');
			},
			'beforeClose': function() {

				this.element.removeClass('overlay-normal');
			}
        });

		//fwd = encodeURIComponent(window.location.href);
		
		var html = [];

		html.push('<div class="overlay-inner">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Επέλεξε μια από τις υπηρεσίες για να συνδεθείς<span class="close" onclick="LoginRegisterBox.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body clr">');

		html.push('<ul class="login-services clr">');
		
		html.push('<li class="facebook">');
		html.push('<a href=\"?action=reqToken&amp;serviceId=3' + (fwd != '' ? '&amp;forward=' + fwd : '') + '\">');
		html.push('<span>Facebook</span>');
		html.push('</a>');
		html.push('</li>');

		html.push('<li class="google">');
		html.push('<a href=\"?action=reqToken&amp;serviceId=2' + (fwd != '' ? '&amp;forward=' + fwd : '') + '\">');
		html.push('<span>Google</span>');
		html.push('</a>');
		html.push('</li>');

		html.push('<li class="twitter">');
		html.push('<a href=\"?action=reqToken&amp;serviceId=1' + (fwd != '' ? '&amp;forward=' + fwd : '') + '\">');
		html.push('<span>Twitter</span>');
		html.push('</a>');
		html.push('</li>');
/*
		html.push('<li class="pathfinder">');
		html.push('<a class=\"inactive\" href=\"javascript:void(0);\">');
		html.push('<span>Pathfinder (ανενεργό)</span>');
		html.push('</a>')
		html.push('</li>');
*/	
		html.push('</ul>');
		
		html.push('<p class="register-notice">Δεν έχεις ακόμη λογαριασμό στο BestPrice; <a href="javascript:void(0);" onclick="LoginRegisterBox.overlay.close();LoginRegisterBox.registerRender();">Δημιούργησε έναν εδώ γρήγορα &amp; εύκολα &rarr;</a></p>')
		
		html.push('</div>');	
		html.push('</div>');
		
		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();	
		
		return true;
	},
	
	load : function() {
			
		if(!this.overlay || !this.overlay.element || !this.overlay.element.getElement('.overlay-body'))
			return;
			
		var body = this.overlay.element.getElement('.overlay-body');
		
		$(body).setStyle('position', 'relative');
		
		$C('div').setStyles({
			'position' 	: 'absolute',
			'top'		: 0,
			'left'		: 0,
			'width'		: (parseInt($(body).getStyle('width')) + 20) + 'px',
			'height'	: (parseInt($(body).getStyle('height')) + 20) + 'px',
			'background': (window.ie ? '#fff' : 'rgba(100, 100, 100, 0.5)'),
			'display'	: 'table',
			'text-align': 'center',
			'color'		: 'white',
			'font-size'	: '26px',
			'text-shadow': '1px 1px 1px #333'
		}).setHTML('<span style="display: table-cell; vertical-align: middle;"><em style="display: block;width: 300px;margin: 0 auto;box-shadow: 1px 1px 1px #666; background: white;padding: 10px;font-style: normal;color: #333;text-shadow: none;">Παρακαλώ περίμενε&hellip;<br/><progress></progress></em></span>').injectIn($(body));
	},
	
	registerRender : function(fwd, youNeedToLogin) {
		
		var fwd = (typeof fwd != 'undefined' && fwd != '' ? fwd : '');
		
		this.overlay = this.overlay || new Overlay('', {
			
			'duration'	: 400,
			'className'	: 'overlay',
			'onOpen'	: function() {

				this.element.addClass('overlay-normal');
			},
			'beforeClose': function() {

				this.element.removeClass('overlay-normal');
			}
        });

		var html = [];

		html.push('<div class="overlay-inner">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Είσοδος ή εγγραφή στο BestPrice<span class="close" onclick="LoginRegisterBox.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body clr">');
		
		if(typeof youNeedToLogin != 'undefined' && youNeedToLogin === true) {
			
			html.push('<div class="login-first">');
			html.push('<p>Πρέπει να είσαι συνδεδεμένος για να κάνεις αυτήν την ενέργεια</p>');
			html.push('</div>');
		}

		html.push('<div class="services">');
		
		html.push('<h4>Είσοδος ή εγγραφή με χρήση:</h4>');
		
		html.push('<ul>');
		
		html.push('<li class="facebook">');
		html.push('<a onclick=\"LoginRegisterBox.load();\" href=\"?action=reqToken&amp;serviceId=3' + (fwd != '' ? '&amp;forward=' + fwd : '') + '\">');
		html.push('<span>Facebook</span>');
		html.push('</a>');
		html.push('</li>');

		html.push('<li class="google">');
		html.push('<a onclick=\"LoginRegisterBox.load();\" href=\"?action=reqToken&amp;serviceId=2' + (fwd != '' ? '&amp;forward=' + fwd : '') + '\">');
		html.push('<span>Google</span>');
		html.push('</a>');
		html.push('</li>');

		html.push('<li class="twitter">');
		html.push('<a onclick=\"LoginRegisterBox.load();\" href=\"?action=reqToken&amp;serviceId=1' + (fwd != '' ? '&amp;forward=' + fwd : '') + '\">');
		html.push('<span>Twitter</span>');
		html.push('</a>');
		html.push('</li>');

		html.push('</ul>');
		
		html.push('</div>');
		
		html.push('<div class="reasons">');
		html.push('<h4>Λόγοι εγγραφής:</h4>');
		html.push('<p class="note">Η εγγραφή δεν παίρνει περισσότερο από 1 λεπτό</p>');
		html.push('<ul>');
		html.push('<li>Δραστηριότητα φίλων</li>');
		html.push('<li>Λίστες προϊόντων (θέλω, έχω)</li>');
		html.push('<li>Ειδοποίηση για ημερήσιες προσφορές</li>');
		html.push('<li>Ειδοποίηση πτώσης τιμής</li>');
		html.push('<li>Αξιολόγηση προϊόντων/καταστημάτων</li>');
		html.push('<li>Προτεινόμενα προϊόντα</li>');
		html.push('<li>(soon) Συμμετοχή σε εκπτωτικά προγράμματα</li>');
		html.push('<li>(soon) Ενημέρωση για νέα προϊόντα</li>');
		html.push('</ul>');
		
		html.push('</div>');
		
		html.push('</div>');
		
		if ((new Date()).format('Y') == 2011) {
			html.push('<div class="overlay-footer santa-overlay">Ήσουν καλό παιδί φέτος;</div>');
		} else {
			html.push('<div class="overlay-footer login-overlay">BestPrice - the 1st and best</div>');
		}
			
		html.push('</div>');

		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();	
	}
}

var CreateAccount = {
	
	initialize : function() {
		
		if(typeof(oAuthProps) == 'undefined')
			return;
			
		this.render.delay(0, this);
	},
	
	render : function() {
		
		this.overlay = new Overlay('', {
			'duration' 	: 400,
			'className'	: 'overlay',
			'onOpen'	: function() {

				this.element.addClass('overlay-normal');
			},
			'beforeClose': function() {

				this.element.removeClass('overlay-normal');
			}
		});
		
		var html 		= [];

		html.push('<div class="overlay-inner">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Δημιουργία λογαριασμού<span class="close" onclick="CreateAccount.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body">');

		html.push('<form id="new-account" class="new-account" method="post" action="">');
		
		html.push('<p id="username-container" class="clr"><label for="new-username">Username</label>');
		html.push('<input class="field" autofocus type="text" name="username" autocomplete="off" value="' + oAuthProps.username + '" id="new-username"/></p>');
		
		html.push('<p id="email-container" class="clr"><label for="new-email">Email</label>');
		html.push('<input class="field" type="email" autocomplete="off" name="email" id="new-email" value="' + oAuthProps.email + '" /></td></p>');

		html.push('<p class="input-container"><input type="checkbox" checked="checked" id="newsletter" name=\"newsletter\"/>&nbsp;Επιθυμώ να λαμβάνω newsletter (~1 email την εβδομάδα)</p>');
		
		html.push('<p class="input-container"><input disabled="disabled" type="checkbox" checked="checked" id="terms"/>&nbsp;Συμφωνώ με τους <a href="/about/terms" target="terms">όρους χρήσης</a></p>');
		
		html.push('<p class="input-container"><input class="button" type="submit" value="Δημιουργία"/> -ή- <a href="javascript:void(0);" onclick="CreateAccount.overlay.close();">κλείσιμο</a></p>');
		html.push('<input type="hidden" name="action"  value="doSignup"/>');
		html.push('<input type="hidden" name="token"   value="' + oAuthProps.token + '" />');
		html.push('<input type="hidden" name="secret"  value="' + oAuthProps.secret + '" />');
		html.push('<input type="hidden" name="props"   value="' + oAuthProps.props + '" />');
		html.push('<input type="hidden" name="assocId" value="' + oAuthProps.assocId + '" />');
		html.push('<input type="hidden" name="service" value="' + oAuthProps.service + '" />');
		html.push('<input type="hidden" name="pfSecret"value="' + oAuthProps.pfSecret + '"/>');
		html.push('</form>');
		
		html.push('</div>');	
		html.push('</div>');
		
		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();
		
		$C('span', { 'id' : 'uname-notice' }).injectIn($('username-container')).hide();
		$C('span', { 'id' : 'email-notice' }).injectIn($('email-container')).hide();
		
		$('new-username').addEvent('keyup', this.checkUsername.bind(this));
		$('new-email').addEvent('keyup', this.checkEmail.bind(this));
		
		$('new-account').addEvent('submit', function(event) { CreateAccount.beforeSubmit(event); });
		
		this.checkUsername();
		
		$('new-username').focus();
	},
	
	checkUsername : function() {
		
		var uname 		= $('new-username').getValue();
		var unameNotice	= $('uname-notice');
		
		if(uname == "") {
			
			unameNotice.hide();
			return;
		}
		
		if(uname.length < 3) {
			
			unameNotice.setHTML('Το username πρέπει να είναι > 2 χαρακτήρες').show();
			return;
		}
		
		new Ajax.RPC({

			'host' 	: (window.location.host.indexOf('dev') !== -1 ? '10.5.5.8' 	: '10.5.5.13'),
			'port' 	: (window.location.host.indexOf('dev') !== -1 ? 30076		: 30032),
			
			'onSuccess' : function() {
		
				var result = this.responseJSON;
			
				if(result.faultCode && result.faultCode == 2)
					unameNotice.setHTML('Το username υπάρχει ήδη').show();
				else
					unameNotice.hide();
			}
	
		}).send("bestprice.CheckUsername", uname)
	},
	
	checkEmail : function() {
		
		var email 		= $('new-email').getValue();
		var emailNotice	= $('email-notice');
		
		if(email == "") {
			
			emailNotice.hide();
			return;
		}
		
		if(!email.isValidEmail())
			emailNotice.setHTML('Το email δεν είναι έγκυρο').show();
		else
			emailNotice.hide();
	},
	
	beforeSubmit : function(event) {
		
		event.preventDefault();

		if($('new-username').getValue() == "") {
		
			$('uname-notice').setHTML('Το πεδίο είναι κενό').show();
			$('new-username').focus();
			
			return;
		}

		if($('new-email').getValue() == "") {
		
			$('email-notice').setHTML('Το πεδίo είναι κενό').show();
			$('new-email').focus();
			
			return;
		}
		
		if(!$('uname-notice').isHidden()) {
			
			$('new-username').focus();
			
			return;
		}
		
		if(!$('email-notice').isHidden()) {
			
			$('new-email').focus();
			
			return;
		}
		
		$('new-account').submit();
	}
}

var Alerts = {

	'messages' : {
		
		1	: 'Αποτυχία σύνδεσης',
		2	: 'Λάθος όνομα χρήστη/κωδικός πρόσβασης',
		3	: 'Το email είναι κενό',
		4	: 'Το όνομα είναι κενό',
		5	: 'Το επίθετο είναι κενό',
		6	: 'Το όνομα χρήστη είναι κενό',
		7	: 'Το όνομα χρήστη περιέχει μη επιτρεπτούς χαρακτήρες',
		8	: 'Ο κωδικός πρόσβασης είναι κενός',
		9	: 'Ο κωδικός πρόσβασης θα πρέπει να είναι διαφορετικός από το όνομα χρήστη',
		10	: 'Ο κωδικός πρόσβασης είναι παρόμοιος με το όνομα χρήστη, πληκτρολόγησε κάποιον άλλο κωδικό',
		11	: 'Το όνομα χρήστη δεν είναι έγκυρο',
		12	: 'Αυτό το όνομα χρήστη υπάρχει ήδη',
		13	: 'Το όνομα χρήστη περιέχει μη επιτρεπτούς χαρακτήρες ή είναι πολύ μικρό',
		14	: 'Το όνομα χρήστη περιέχει μη επιτρεπτούς χαρακτήρες',
		15	: 'Τα cookies δεν είναι ενεργοποιημένα ή υπάρχει κάποιο λάθος με την ημερομηνία του υπολογιστή',
		16	: 'Κάποια απαραίτητα πεδία δεν βρέθηκαν',
		17	: 'Η εγγραφή απέτυχε',
		18	: 'Εμφανίστηκαν προβλήματα στον proxy server',
		19	: 'Ο λογαριασμός έχει απενεργοποιηθεί',
		20	: 'Η σύνδεση δεν ήταν δυνατή',
		21	: 'Σφάλμα, προσπάθησε ξανά',
		22	: 'Δεν βρέθηκαν cookies με τις απαραίτητες πληροφορίες',
		23	: 'Κάποια απαραίτητα δεδομένα για την σύνδεση του τρίτου λογαριασμού δεν βρέθηκαν',
		24	: 'Παρουσιάστηκε σφάλμα κατά τη σύνδεση. Δοκίμασε ξανά',
		25	: 'Η επικοινωνία με το Twitter απέτυχε, προσπάθησε ξανά',
		26	: 'Σφάλμα κατά την λήψη των πληροφοριών του χρήστη',
		27	: 'Οι πληροφορίες για την σύνδεση των λογαριασμών είναι ελλιπείς',
		28	: 'Αντιμετωπίζουμε τεχνικά προβλήματα, προσπάθησε ξανά αργότερα',
		29	: 'Σφάλμα, προσπάθησε ξανά',
		30	: 'Δεν βρέθηκαν συνδεδεμένοι λογαριασμοί',
		31	: 'Σφάλμα κατά την δημιουργία νέου κωδικού πρόσβασης, προσπάθησε ξανά',
		32	: 'Ο σύνδεσμος ανάκτησης κωδικού δεν είναι έγκυρος, προσπάθησε ξανά',
		33	: 'Το email θα πρέπει να ανήκει σε μια τρίτη υπηρεσία (Gmail, Hotmail κλπ).',
		34	: 'Η επικοινωνία με το Google απέτυχε, προσπάθησε ξανά',
		35	: 'Δεν μπορείς να αποσυνδέσεις τον λογαριασμό σου',
		36	: 'Σφάλμα κατά την επαλήθευση των στοιχείων, δοκίμασε ξανά',
		37	: 'Δεν θα λάβεις ξανά ενημερωτικά email aπό το BestPrice'
	},
	
	initialize : function() {
		
		if(window.location.hash == "" || window.location.hash.indexOf('error') == -1)
			return;
	
		this.id = (window.location.hash.split(/error/)[1] ? parseInt(window.location.hash.split(/error/)[1]) : 0);

		if(this.id == 0)
			return;
	
		if(!this.messages[this.id])
			this.id = 29;
			
		if(window.ie7 || window.ie8)
			window.location.hash = " ";
		else
			window.location.hash = "";
			
		this.render.delay(0, this, this.messages[this.id]);
	},
	
	render : function(messageString) {
		
		this.overlay = new Overlay('', {
			'duration' 	: 400,
			'className'	: 'overlay',
			'onOpen'	: function() 	{ this.element.addClass('overlay-normal'); },
			'beforeClose': function() 	{ this.element.removeClass('overlay-normal'); }
		});
		
		var html 		= [];

		html.push('<div class="overlay-inner">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>' + (this.id == 37 ? 'Διακοπή αποστολής email' : 'Σφάλμα') + '<span class="close" onclick="Alerts.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body">');

		html.push('<p class=\"error-message\">' + messageString + '</p>');
		
		html.push('</div>');	
		html.push('</div>');
		
		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();
	}
}

var Welcome = {

	initialize : function() {

		if(window.location.hash == "" || window.location.hash != "#welcome")
			return;

		if(window.ie7 || window.ie8)
			window.location.hash = " ";
		else
			window.location.hash = "";

		this.render();
	},
	
	render : function() {
		

		var html 		= [];

		html.push('<h6>Καλώς ήρθες στο Bestprice!<span class="close" onclick="$(\'contextual-welcome\').remove();">×</span></h6>');
		html.push('<p>Κάνε κλικ στο username σου για να αλλάξεις τα στοιχεία του λογαριασμού σου</p>');

		$C('div', {
			'id' : 'contextual-welcome'
		}).setClass('contextual').setHTML(html.join('')).injectIn($('wrapper'));
	}
}

var ChangeAvatar = {

	initialize : function() {
		
		if(!$('change-avatar'))
			return;
		
        this.overlay = new Overlay('', {
			'duration'	: 400,
			'className'	: 'overlay',
			'onOpen'	: function() {

				this.element.addClass('overlay-normal');
			},
			'beforeClose': function() {

				this.element.removeClass('overlay-normal');
			}
        });

		$('change-avatar').addEvent('click', this.render.bind(this));
	},

	render : function() {

		var html = [];

		html.push('<div class="overlay-inner">');

		html.push('<div class="overlay-header">');
		html.push('<h4>Αλλαγή avatar<span class="close" onclick="ChangeAvatar.overlay.close();">x</span></h4>');
		html.push('</div>');

		html.push('<div class="overlay-body">');
		
		html.push('<form method="post" action="" enctype="multipart/form-data">');
		
		var extAvatars = false;
		
		if(Avatars.twitter || Avatars.google || Avatars.facebook || Avatars.gravatar) {
		
			extAvatars = true;
			
			html.push('<p>');
			html.push('Χρήση υπάρχοντος avatar από τρίτες υπηρεσίες:');
			html.push('</p>');		
			
			html.push('<ul class="external-avatar clr">');

			html.push('<li>');
			html.push('<label for="none-avatar"><img alt="Twitter avatar" width="50" height="50" src="' + Avatars.current + '"/></label>');
			html.push('<input type="radio" value="" checked="checked" id="none-avatar" name="avatar-image"/>');
			html.push('<p>Τρέχον</p>');
			html.push('</li>');
			
			if(Avatars.twitter && Avatars.twitter != "") {
			
				html.push('<li>');
				html.push('<label for="twitter-avatar"><img alt="Twitter avatar" width="50" height="50" src="' + decodeURIComponent(Avatars.twitter) + '"/></label>');
				html.push('<input type="radio" value="' + Avatars.twitter + '" id="twitter-avatar" name="avatar-image"/>');
				html.push('<p>Twitter</p>');
				html.push('</li>');
			}	

			if(Avatars.google && Avatars.google != "") {
			
				html.push('<li>');
				html.push('<label for="google-avatar"><img alt="Google avatar" width="50" height="50" src="' + decodeURIComponent(Avatars.google) + '"/></label>');
				html.push('<input type="radio" value="' + Avatars.google + '" id="google-avatar" name="avatar-image"/>');
				html.push('<p>Google</p>');
				html.push('</li>');
			}
		
			if(Avatars.facebook && Avatars.facebook != "") {
			
				html.push('<li>');
				html.push('<label for="facebook-avatar"><img alt="Facebook avatar" width="50" height="50" src="' + decodeURIComponent(Avatars.facebook) + '"/></label>');
				html.push('<input type="radio" value="' + Avatars.facebook + '" id="facebook-avatar" name="avatar-image"/>');
				html.push('<p>Facebook</p>');
				html.push('</li>');
			}
		
			if(Avatars.gravatar && Avatars.gravatar != "") {
			
				html.push('<li>');
				html.push('<label for="gravatar"><img alt="Gravatar" width="50" height="50" src="' + decodeURIComponent(Avatars.gravatar) + '"/></label>');
				html.push('<input type="radio" value="' + Avatars.gravatar + '" id="gravatar" name="avatar-image"/>');
				html.push('<p>Gravatar</p>');
				html.push('</li>');
			}
				
			html.push('</ul>');
		}
		
		html.push('<p>');
		html.push((extAvatars ? 'Ή ορισμός' : 'Ορισμός') + ' από δική σου φωτογραφία: ');
		html.push('<input type="file" name="avatar-file" value=""/>');
		html.push('</p>');
		
		html.push('<p class="avatarsubmit-container">');
		html.push('<input type="hidden" name="ak" value="' + window.User.ak + '"/>');
		html.push('<input type="hidden" name="action" value="setAvatar"/>');
		html.push('<input type="submit" class="button" name="setavatar" value="Αλλαγή avatar"/> ή <a href="javascript:void(0);" onclick="ChangeAvatar.overlay.close();">κλείσιμο</a>');
		html.push('<a id="delete-avatar" href="?action=deleteAvatar&amp;ak=' + window.User.ak + '">Διαγραφή avatar</a>')
		html.push('</p>');
		
		html.push('</form>')
			
		html.push('</div>');	
		html.push('</div>');

		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();	
	}
}

var MerchantReviewForm = {
	
	initialize : function() {
		
		if(!$('mreview-form'))
			return;
			
		Pathfinder.Fields.initialize();
			
		$('mreview-form').addEvent('submit', function(event) {
		
			event.preventDefault();
	
			if(parseInt($('review-stars-0').getValue()) == 0) {
				
				alert('Πρέπει να βαθμολογήσεις το ηλεκτρονικό κατάστημα πριν καταχωρήσεις την αξιολόγησή σου.');
				return false;
			}

			if($('order_number').getValue() == "") {
				
				alert('Πρέπει να εισάγεις τον αριθμό παραγγελίας πριν την αποστολή της αξιολόγησής σου.');
				return false;
			}
			
			MerchantReviewForm.submitForm();
		});
		
		$$('[id^="review-stars-container-"]').each(function() {
		
			var id = parseInt(this.id.split(/-stars-container-/)[1]);

			$(this).addEvent('mouseleave', function() {
			
				var value = parseInt($('review-stars-' + id).getValue());
				
				MerchantReviewForm.updateStars(value, id);
			});

			$(this).getElements('strong').addEvent('mouseenter', function() {

				var regExp 	= "star-" + id + "-";
				var value 	= parseInt($(this).id.split(regExp)[1]);

				MerchantReviewForm.updateStars(value, id);
			});
			
			$(this).getElements('strong').addEvent('click', function() {

				var regExp 	= "star-" + id + "-";
				var value 	= parseInt($(this).id.split(regExp)[1]);

				$('review-stars-' + id).setValue(value);
			});
		});	
		
		new CCounter($('review-descr'), {
			
			'chars' 	: 6000, 
			onChange 	: function(charsObj) {
				
				var text = '';
				
				if(charsObj.remaining == 1)
					text = 'Απομένει 1 χαρακτήρας';
				else
					text = 'Απομένουν ' + charsObj.remaining + ' χαρακτήρες';
					
				$('.descr-container .tip').setHTML(text);
			}
		});	
	},
	
	submitForm : function() {

		var parameters = {
			'action' 		: 'submitMerchantReview',
			'ak'			: window.User.ak,
			'isAjax'		: true,
			'review-stars-0': parseInt($('review-stars-0').getValue()),
			'review-stars-1': parseInt($('review-stars-1').getValue()),
			'review-stars-2': parseInt($('review-stars-2').getValue()),
			'review-stars-3': parseInt($('review-stars-3').getValue()),
			'review-descr'	: $('review-descr').getValue(),
			'order-number'	: $('order_number').getValue()
		};
	
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				if(parseInt(response.res.faultCode) > 0) {
				
					if(parseInt(response.res.methodCode) == 20) {
						
						alert('Έχεις αφήσει ήδη μια αξιολόγηση για αυτό το κατάστημα.');
						$('my-review').remove();
											
					} else if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else						
						alert('Σφάλμα: ' + response.res.faultString);
					
				} else {
					
					alert('Σε ευχαριστούμε για την αξιολόγησή σου! Το προσωπικό του BestPrice θα την αξιολογήσει και θα την ενεργοποιήσει μέσα στις επόμενες 24 ώρες.');					

					$('my-review').remove();
					$('reviews').getElement('h5 .more') && $('reviews').getElement('h5 .more').remove();
					$('item-meta').getElement('.review-it') && $('item-meta').getElement('.review-it').remove();
				}
				
				MerchantReviewForm.resetForm();
			},
		
			'parameters' : parameters
		
		}).send();
	},

	resetForm : function() {
		
		$('review-descr') && $('review-descr').setValue('');

		$$('[id^="review-stars-container-"]').each(function() {
		
			var id = parseInt(this.id.split(/-container-/)[1]);
			
			$('review-stars-' + id).setValue('0');
			
			$(this).getElements('strong').each(function() { this.removeClass('hi'); });
		});
	},
	
	updateStars : function(value, id) {
		
		for(var i = 1; i <= 5; i++) {
		
			var el = $('review-star-' + id + '-' + i);
			
			if(i <= value)
				$(el).setClass('hi');
			else
				$(el).removeClass('hi');
		}
		
		var text = '';
		
		if(value == 1)
			text = 'Απαίσιο';
		else if(value == 2)
			text = 'Κακό';
		else if(value == 3)
			text = 'Μέτριο';
		else if(value == 4)
			text = 'Καλό';
		else if(value == 5)
			text = 'Φοβερό';
			
		$('review-stars-container-' + id).getElement('.caption').setHTML(text);
	}
}

var ReviewForm = {
	
	'pros'	: [],
	'cons'	: [],
	
	initialize : function() {
		
		if(!$('review-form'))
			return;
		
		Pathfinder.Fields.initialize();
				
		this.submit = $('review-form').getElement('input[type="submit"]');

		$('review-form').addEvent('submit', function(event) {
		
			event.preventDefault();
	
			if(parseInt($('review-stars').getValue()) == 0) {
				
				alert('Πρέπει να βαθμολογήσεις το προϊόν πριν καταχωρήσεις την αξιολόγησή σου');
				
				return false;
			}
						
			//ReviewForm.addTerm(0);
			//ReviewForm.addTerm(1);
			
			//if(ReviewForm.pros.length > 0)
			//	$('pros-terms-values').value = ReviewForm.pros.join(',');
				
			//if(ReviewForm.cons.length > 0)
			//	$('cons-terms-values').value = ReviewForm.cons.join(',');
				
			ReviewForm.submitForm();
		});
		
		$('review-stars-container').getElements('strong').addEvent('mouseenter', function() {
		
			$('review-stars-container').getElements('strong.hi').each(function() { this.setStyle(''); });

			var id = parseInt($(this).id.split(/star-/)[1]);
			
			ReviewForm.updateStars(id);
		});
	
		$('review-stars-container').addEvent('mouseleave', function() {
		
			var value = parseInt($('review-stars').getValue());
			
			ReviewForm.updateStars(value);
		});
		
		$('review-stars-container').getElements('strong').addEvent('click', function() {
		
			var id = parseInt($(this).id.split(/star-/)[1]);

			$('review-stars').setValue(id);

			$('review-stars-container').getElements('strong.hi').each(function() {

				new Fx.Style(this, 'color', { 'duration' : 300 }).start('#000000', '#479ee7');

				$('review-title').focus();
			});
		});

		/*		
		$('review-pros').addEvent('keydown', function(event) {
			
			if(event.code == 13) {
				
				event.preventDefault();
				
				ReviewForm.addTerm(0);
			}
		});

		$('review-cons').addEvent('keydown', function(event) {

			if(event.code == 13) {
				
				event.preventDefault();

				ReviewForm.addTerm(1);
			}
		});
		
		$('add-pros').addEvent('click', function(event) { ReviewForm.addTerm(0); });
		$('add-cons').addEvent('click', function(event) { ReviewForm.addTerm(1); });
		*/
		new CCounter($('review-descr'), {
			
			'words' 	: 20, 
			'expand'	: true,
			onChange 	: function(charsObj) {

				var text = '';
				
				if(this.words.remaining == 1)
					text = 'Απομένει 1 λέξη';
				else if(this.words.remaining <= 10)
					text = 'Απομένουν ' + this.words.remaining + ' λέξεις';
					
				$('.descr-container .tip').setHTML(text);

				if(this.words.remaining <= 10)
					$('.descr-container .tip').show();
			}
		});	
		
		new CCounter($('review-title'), {
			
			'chars' 	: 140, 
			onChange 	: function(charsObj) {

				var text = '';
				
				if(charsObj.remaining == 1)
					text = 'Απομένει 1 χαρακτήρας';
				else if(charsObj.remaining <= 10)
					text = 'Απομένουν ' + charsObj.remaining + ' χαρακτήρες';
					
				$('title-remaining').setHTML(text);

				if(charsObj.remaining <= 10)
					$('title-remaining').show();
			}
		});
	},
	
	submitForm : function() {

		var parameters = {
			'action' 		: 'submitItemReview',
			'ak'			: window.User.ak,
			'isAjax'		: true,
			'review-stars'	: parseInt($('review-stars').getValue()),
			'item-id'		: parseInt($('have-want-container').getProperty('data-pid')),
			'review-title'	: $('review-title').getValue(),
			'review-descr'	: $('review-descr').getValue()/*,
			'pros-terms'	: $('pros-terms-values').getValue(),
			'cons-terms'	: $('cons-terms-values').getValue()*/
		};
	
		var submitText		= this.submit.getValue();

		this.submit.disabled = true;
		this.submit.setValue('Φόρτωση...');

		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				if(!response.res) {
					
					alert('Εμφανίστηκε κάποιο πρόβλημα, προσπάθησε ξανά.');
				
					ReviewForm.submit.disabled = false;
					ReviewForm.submit.setValue(submitText);
				
					return;
				}

				if(parseInt(response.res.faultCode) > 0) {
					
					if(parseInt(response.res.methodCode) == 20)
						alert('Έχεις αφήσει ήδη μια αξιολόγηση για αυτό το προϊόν.');
					 else if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else						
						alert('Σφάλμα: ' + response.res.faultString);
					
					ReviewForm.submit.disabled = false;
					ReviewForm.submit.setValue(submitText);
						
				} else
					location.reload();
			},
		
			'parameters' : parameters
		
		}).send();
	},

	resetForm : function() {
		
		$('review-stars-container').getElement('.caption').setHTML('').hide();
		$('review-title').setValue('');
		$('review-descr').setValue('');
		$('review-stars').setValue('0');

		$('title-remaining').hide();
		$('.descr-container .tip').hide();

//		$('pros-terms-values').setValue('');
//		$('cons-terms-values').setValue('');
		
		$('review-stars-container').getElements('strong').each(function() {
			this.removeClass('hi');
		});
		
//		$('pros-terms').setHTML('').hide();
//		$('cons-terms').setHTML('').hide();
		
		ReviewForm.pros = [];
		ReviewForm.cons	= [];
	},
	
	updateStars : function(id) {
		
		for(var i = 1; i <= 5; i++) {
			
			var el = $('review-star-' + i);
			
			if(i <= id)
				$(el).setClass('hi');
			else
				$(el).removeClass('hi');
		}
		
		var text = '';
		
		if(id == 1)
			text = 'Απαίσιο';
		else if(id == 2)
			text = 'Κακό';
		else if(id == 3)
			text = 'Μέτριο';
		else if(id == 4)
			text = 'Καλό';
		else if(id == 5)
			text = 'Φοβερό';
			
		$('review-stars-container').getElement('.caption').setHTML(text);
	},
	
	addTerm : function(isCon) {
		
		var element = (isCon == 0 ? $('review-pros') : $('review-cons'));
		var termsEl	= (isCon == 0 ? $('pros-terms') : $('cons-terms'));
		var term 	= $(element).getValue().trim();
		var termAr	= (isCon ? this.cons : this.pros);
	
		if(term == '') {
		
			$(element).focus();
			
			return;
		}
		
		if(termsEl.isHidden())	
			termsEl.show();
			
		$(element).setValue('');
		$(element).focus();
		
		if(termAr.indexOf(term) > -1)
			return;
			
		$C('span', {
			'title' : 'Κλικ για διαγραφή όρου'
		}).setHTML(term).injectIn($(termsEl)).addEvent('click', function() { ReviewForm.removeTerm(this, isCon); });
		
		termAr.push(term);
	},
	
	removeTerm : function(element, isCon) {
		
		var term 	= element.innerHTML;
		var termAr	= (isCon ? this.cons : this.pros);
		var termsEl	= (isCon == 0 ? $('pros-terms') : $('cons-terms'));
		
		$(element).remove();
		
		var index	= termAr.indexOf(term);
		
		termAr.splice(index, 1);
		
		if(termAr.length == 0)
			termsEl.hide();
	}
}

function Review(reviewElement, isMerchant) {
	
	// get the DOM elements
	this.element 			= reviewElement;
	this.id					= parseInt($(reviewElement).getProperty('data-review'));
	this.isMerchant			= ($(reviewElement).getProperty('data-type') == "merchant");
	this.reportElement		= $(reviewElement).getElement('.report-review');
	this.deleteElement		= $(reviewElement).getElement('#delete-review');
	this.helpfulContainer	= $(reviewElement).getElement('.helpful');
	this.isHelpfulElement	= $(reviewElement).getElement('.is-helpful');
	this.isNotHelpfulElement= $(reviewElement).getElement('.is-not-helpful');
	
	var self = this;
	
	// hook the event listeners
	this.reportElement && this.reportElement.addEvent('click', function(event) {
	
		event.preventDefault();
	
		self.report();
	});
	
	this.deleteElement && this.deleteElement.addEvent('click', function(event) {
	
		event.preventDefault();
		self.removeReview();
	});
	
	this.isHelpfulElement && this.isHelpfulElement.addEvent('click', function(event) {
	
		event.preventDefault();
	
		self.isHelpful(true);
	});
	
	this.isNotHelpfulElement && this.isNotHelpfulElement.addEvent('click', function(event) {
	
		event.preventDefault();
	
		self.isHelpful(false);
	});
}

Review.prototype = {
	
	'ajaxCall' :  function(method, extraOptions, onSuccessCallback) {

		var parameters 	= {};
		var self		= this;
	
		// default parameters for each review action
		parameters = {
			'action' 	: method,
			'ak'		: window.User.ak,
			'isAjax'	: true,
			'reviewId'	: this.id
		};
		
		// add any additional parameters
		each(extraOptions, function(value, key) { parameters[key] = value; });

		// make the call
		new Ajax('post', {
		
			onSuccess : function()	{
			
				// get the response
				var response = this.responseJSON;

				if(parseInt(response.res.faultCode) > 0) {

					if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else						
						alert('Σφάλμα: ' + response.res.faultString);

					return;
				}
			
				// if the callback exists, fire it with this argument
				// scope == review	
				onSuccessCallback && onSuccessCallback.call(self, response.res);
			},
		
			// add the parameters
			'parameters' : parameters
		
		}).send();	
	},
	
	'report' : function() {

		var answer = confirm("Είσαι σίγουρος/η ότι θέλεις να αναφέρεις την αξιολόγηση;");
		
		if(!answer)
			return;
			
		this.ajaxCall((this.isMerchant ? 'reportMerchantReview' : 'reportItemReview'), {}, function(response) {
		
			if(response == true)
				alert('Ευχαριστούμε! Το προσωπικό του BestPrice θα εξετάσει την αναφορά σου σύντομα.');
			else
				alert('Εμφανίστηκε κάποιο πρόβλημα κατά την καταχώρηση της αναφοράς σου, προσπάθησε ξανά.');
		});
	},
	
	'removeReview'  : function() {

		if(!this.isMerchant)
			return;

		var answer = confirm("Είσαι σίγουρος/η ότι θέλεις να διαγράψεις την αξιολόγηση;");
		
		if(!answer)
			return;
			
		this.ajaxCall((this.isMerchant ? 'deleteMerchantReview' : 'deleteItemReview'), {}, function(response) {
		
			if(response == true)
				alert('Η αξιολόγησή σου θα αφαιρεθεί από το σύστημα μέσα στις επόμενες 24 ώρες.');
			else
				alert('Σφάλμα κατά την καταχώρηση του αιτήματος διαγραφής. Προσπάθησε ξανά.');
		});	
	},

	'isHelpful' : function(isHelp) {
	
		this.ajaxCall((this.isMerchant ? 'isMerchantReviewHelpful' : 'isItemReviewHelpful'), {'helpful' : (isHelp ? 1 : 0)}, function(response) {
		
			var good				= parseInt(response.good);
			var bad					= parseInt(response.bad);
			var helpfulTotal 		= good + bad;

			if(helpfulTotal > 0) {

				var html = '';
				
				html += good;
				html += (good != helpfulTotal ? " από " + helpfulTotal : "");
				html += " ";
				html += (helpfulTotal > 1 ? "άτομα την βρήκαν" : "άτομο την βρήκε");
				html += " χρήσιμη";
				
				$(this.helpfulContainer).setHTML(html);
			}
		});
	}
}

Reviews = {

	initialize : function() {
		
		if(!$('.reviews-list'))
			return;
		
		this.reviews = [];
			
		var reviews = $('.reviews-list').getElements('li');
		
		if(reviews.length == 0)
			return;
			
		reviews.each(function() {
			
			Reviews.reviews.push(new Review(this));
		});
	}
}

CategoriesHeader = {

	initialize : function() {
		
		if(!$('header-categories'))
			return;

		this.toggler 	= $('header-categories');
		this.marker		= $(this.toggler).getElement('em');
		this.popup		= $('header-categories-popup');
		
		CategoriesHeader.toggler.addEvent('click', this.toggle.bind(this));
		
		document.addEvent('click', function(event) {

			if(	CategoriesHeader.popup && 
				!CategoriesHeader.toggler.contains(event.target) &&
				!CategoriesHeader.popup.contains(event.target) && 
				event.target.id != 'header-categories-popup' && 
				event.target.id != 'header-categories'
			) {
				CategoriesHeader.hide();
			}
		});
		
		document.addEvent('keyup', function(event) { 
			
			if(event.code == 27) {
				
				if(!CategoriesHeader.popup.isHidden())
					CategoriesHeader.hide();
			}
		});
	},

	hide : function() {
		
		this.popup.hide();
		this.marker.setHTML('+');
		this.toggler.removeClass('opened');		
	},
	
	toggle : function() {

		if(!this.toggler.hasClass('opened'))
			UserMenu.hide();
			
		this.marker.setHTML((this.marker.innerHTML == '+' ? '-' : '+'));
		this.popup.toggle();
		this.toggler.toggleClass('opened');
	}
}

SearchFeedback = {

	initialize : function() {
		
		if(!$('search-feedback') && !$('help-search') && !$('feedback-side'))
			return;
			
		$('search-feedback') && $('search-feedback').getElements('a').addEvent('click', function() { SearchFeedback.send(this, $('search-feedback')); });	
		
		$('help-search') && $('help-search').addEvent('click', function() { SearchFeedback.send(this, this); });

		if($('feedback-side')) { 
		
			if(0 && !window.hasEvent('scroll')) {

				$('feedback-side').setStyles({
					'position' : 'relative',
					'-webkit-transition': 'all .3s ease-in'
				});
				
				var posY = $('feedback-side').getPosition().y;
				
				window.addEvent('scroll', function(event) {

					var scrollTop = window.getScrollTop();		
					
					if(scrollTop > posY)
						$('feedback-side').setStyle('top', (20 + scrollTop - posY) + 'px');
					else
						$('feedback-side').setStyle('top', 0);
				});
			}
			
			$('feedback-side').getElements('a').addEvent('click', function() { SearchFeedback.send(this, $('feedback-side')); });
			
		}

		this.overlay = new Overlay('', {
			
			'duration'		: 400,
			'className'		: 'overlay',
			'onOpen'	: function() {

				this.element.addClass('overlay-normal');
			},
			'beforeClose': function() {

				this.element.removeClass('overlay-normal');
			}
        });
	},
	
	send : function(element, parentElement) {
		
		this.choice = ($(element).getProperty('data-choice') == "yes");
		this.query 	= $(parentElement).getProperty('data-query');
		
		$('search-feedback') && new Fx.Style($('search-feedback'), 'opacity', { 

			'duration' : 300,
			'onComplete' : function() { $('search-feedback').remove(); }

		}).start(1, 0);
		
		var html = [];

		html.push('<div class="overlay-inner feedback">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Η αξιολόγησή σου για τα αποτελέσματα<span class="close" onclick="SearchFeedback.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body clr">');

		html.push('<div class="success"><p>Βοήθησέ μας να γίνουμε καλύτεροι, αποστέλλοντας την άποψή και αξιολόγησή σου για τα αποτελέσματα της αναζήτησης.</p></div>');
		
		html.push('<h5>1. Το email σου</h5>');
		html.push('<input style="margin: 10px 0; width: 565px; padding: 5px;" type="email" id="feedback-email" class="field" name="email" value="" placeholder="Πληκτρολόγησε το email ώστε να επικοινωνήσουμε μαζί σου σχετικά με την αξιολόγησή σου"/>')
		
		html.push('<h5>2. Οι παρατηρήσεις σου</h5>');
		
		html.push('<textarea placeholder="' + (this.choice ? 'Περιέγραψε την εμπειρία σου' : 'Ανέφερε τον λόγο που δεν σε ικανοποίησαν τα αποτελέσματα της αναζήτησης') + '" id="feedback-reason" name="reason" class="field" style="width: 565px; height: 8em; padding: 5px; margin-top: 10px;"></textarea>');
		
		html.push('<p class="choices"><a class="button" onclick="SearchFeedback.submit();">Αποστολή αξιολόγησης</a> ή <a href="javascript:void(0);" onclick="SearchFeedback.overlay.close();">κλείσιμο</a></p>');
		
		html.push('</div>');	
		html.push('</div>');

		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();
	},
	
	submit : function() {
		
		if($('feedback-email').getValue() != "" && !$('feedback-email').getValue().isValidEmail()) {
		
			alert('Το email δεν είναι έγκυρο');
			
			$('feedback-email').focus();
			
			return;
		}
		
		new Ajax.RPC({

			'host' 	: (window.location.host.indexOf('dev') !== -1 ? '10.5.5.8' 	: '10.5.5.13'),
			'port' 	: (window.location.host.indexOf('dev') !== -1 ? 30076		: 30032),
			
			'onSuccess' : function() {
		
				var result = this.responseJSON;
			
				if(result.faultCode) {
				
					alert('Σφάλμα: ' + result.faultString);
						
				} else {
				
					var overlayBody = $(SearchFeedback.overlay.element).getElement('.overlay-body');

					new Fx.Style($(overlayBody), 'opacity', { 

						'duration' : 300,
						'onComplete' : function() {

							$(overlayBody).setHTML('<p class="thanks-feedback">Ευχαριστούμε!</p><p style="text-align: center;" class="choices"><a href="javascript:void(0);" class="button" onclick="SearchFeedback.overlay.close();">Κλείσιμο</a></p>');

							new Fx.Style($(overlayBody), 'opacity', { 
								'duration' 		: 300
							}).start(0, 1);		
						} 

					}).start(1, 0);
				}
			}
	
		}).send("bestprice.FeedbackSend", $('feedback-email').getValue(), this.choice, this.query, $('feedback-reason').getValue());	
	}
}

MerchantMap = {

	initialize : function() {
		
		if(!$('map-container'))
			return;

		var latlng 	= new google.maps.LatLng(37.955, 23.777);
		this.stores	= JSON.parse(stores);
	    this.map 	= new google.maps.Map($('map-container'), {
			'zoom'					: 6,
			'center'				: latlng,
			'mapTypeId'				: google.maps.MapTypeId.ROADMAP,
			'zoomControl'			: true,
			'disableDefaultUI' 		: true,
			'panControl'			: false,
			'scrollwheel'			: false,
			'scaleControl'			: false,
	      	'zoomControlOptions' 	: { 'style' : google.maps.ZoomControlStyle.SMALL }
	    });
	
		this.renderStores();
	},
	
	renderStores : function() {
		
		var mapBounds = new google.maps.LatLngBounds();

		this.markers = [];
		
		this.stores.each(function() {
		
			var point = new google.maps.LatLng(parseFloat(this.lat), parseFloat(this.lon));
			var marker= new google.maps.Marker({
			
				'position'	: point,
				'infoBox'	: false,
				'map'		: MerchantMap.map,
				'title'		: this.title
			});
			
			marker.infoWindow = new google.maps.InfoWindow({ 'content' : this.title });
			
			google.maps.event.addListener(marker, 'click', function() { 
			
				MerchantMap.markers.each(function() { this.infoWindow.close(); });
				
				this.infoWindow.open(MerchantMap.map, this); 
			});

			mapBounds.extend(point);
			
			MerchantMap.markers.push(marker);
		});
		
		this.map.fitBounds(mapBounds);

		this.listener = google.maps.event.addListener(this.map, "idle", function() { 
			
		  	if(MerchantMap.map.getZoom() > 8) 
				MerchantMap.map.setZoom(8); 
				
		  	google.maps.event.removeListener(MerchantMap.listener); 
		});
		
		this.map.setZoom(8);
	}
}

JoinNetwork = {
	
	initialize : function() {
		
		if(!$('join-button'))
			return;
			
		$('join-button').addEvent('click', function() {
			
			$(this).hide();
			$('join-form').show();
		});
	}
}

ReviewIt = {
	
	initialize : function() {
		
		this.handlers = $('wrapper').getElements('.review-it');
		
		if(this.handlers.length == 0)
			return;
			
		this.fx 		= new Fx.Scroll();
		this.reviewForm = $('my-review');
		
		this.handlers.addEvent('click', this.open.bind(this));
	},
	
	open : function() {
		
		this.reviewForm = this.reviewForm || $('my-review');
		
		if(!this.reviewForm)
			return;
			
		$('page-item') && Product.tabs.select('reviews');
		$('pale-review-it') && $('pale-review-it').remove();
		
		if(this.reviewForm.isHidden()) {
			
			this.reviewForm.setStyles({
				'opacity' 	: 0,
				'display'	: 'block'
			});
		
			new Fx.Style(this.reviewForm, 'opacity', { 'duration' : 500 }).start(0, 1);
		}
	
		this.fx = this.fx || new Fx.Scroll();
		
		$('item-tabs-container') && $('item-tabs-container').getParent() && this.fx.toElement($('item-tabs-container').getParent()); //this.fx.toElement(this.reviewForm);	
	},

	scroll : function() {
		
		this.fx = this.fx || new Fx.Scroll();
		
		this.fx.toElement(this.reviewForm);			
	}
}

Gallery = {
	
	'documentEvent' : false,

	initialize : function() {
		
		if($('page-m'))
			return;
			
		if(!$('item-img'))
			return;
			
		if($('item-img').hasClass('no-img'))
			return;
			
		if(!$('images-dots') && !$('item-img').getElement('.yt-container'))
			return;
	
		this.active 	= 0;
		this.overlayAct = 0;
		this.timerId	= 0;
		this.interval	= 7000;
		this.animating	= false;
		this.opened		= false;

		$('item-img').getElement('.item-images').setStyle('cursor', 'pointer');
		
		this.images	= $('item-img').getElements('.item-images > *');
		this.title	= $('item-header').getElement('h1').innerHTML;
		
		this.overlay = new Overlay('', {
			'duration'		: 400,
			'className'		: 'overlay',
			'onOpen'		: function() { this.element.addClass('overlay-normal'); },
			'beforeClose'	: function() {

				$('overlay-image').setHTML('');
				
				this.element.removeClass('overlay-normal');
				
				Gallery.opened 	= false;
				Gallery.timerId = Gallery.getNext.delay(Gallery.interval, Gallery);
			}
        });

		this.overlay.element.id = 'item-gallery';

		$('item-img').getElement('.item-images').addEvent('click', function() {
			
			clearTimeout(Gallery.timerId);
			
			Gallery.openOverlay(this);
		});			

		if($('images-dots')) {

			this.dots 	= $('images-dots').getElements('li[data-dot]');
			this.dots.addEvent('click', function() {
			
				clearTimeout(Gallery.timerId);
				
				Gallery.selectImage(this, true); 
			});
			
			this.zoomDot = $('images-dots').getElement('li.zoom');
			this.zoomDot.addEvent('click', function() {
				
				clearTimeout(Gallery.timerId);
				Gallery.openOverlay(this);
			});
			
			if(this.dots.length == 0)
				return;
				
			this.timerId = this.getNext.delay(this.interval, this);
		}

		if(!this.documentEvent) {
				
			document.addEvent('keyup', function(event) { 
			
				if(!Gallery.opened)
					return;
					
				if(event.code == 37)	
					Gallery.selectOverlayImage(-1);
				else if(event.code == 39)
					Gallery.selectOverlayImage(1);
			});
		}

		this.documentEvent = true;
	},
	
	playerEnded : function() {
	
		if(this.images.length > 1 && this.active == 0)
			this.timerId = this.getNext.delay(this.interval, this);
	},
	
	openOverlay : function() {
		
		var image	= this.images[this.active];
		var fullUrl = image.getProperty('data-fullsrc');
		
		if(image.getProperty('data-code') && image.getProperty('data-code') != "") {
			
			var html = [];

			html.push('<div class="overlay-inner">');

			html.push('<div class="overlay-header">');
			html.push('<h4>' + Gallery.title + '<span class="close" onclick="Gallery.overlay.close();">x</span></h4>');
			html.push('</div>');

			html.push('<div class="overlay-body clr">');

			html.push('<div id="overlay-image">');
			html.push('<iframe width="600" height="400" src="http://www.youtube.com/embed/' + image.getProperty('data-code') + '?html5=1" frameborder="0" allowfullscreen></iframe>');
			html.push('</div>');
		
			if(Gallery.images.length > 1) {
			
				html.push('<a href="javascript:void(0);" class="previous" onclick="Gallery.selectOverlayImage(-1);">Previous</a>');
				html.push('<a href="javascript:void(0);" class="next" onclick="Gallery.selectOverlayImage(1);">Next</a>');
			}
		
			html.push('</div>');	
			html.push('</div>');

			Gallery.overlay.open(html.join(''));
			Gallery.overlay.element.setStyle('z-index', '99999999');
			Gallery.overlay.pos();
			
			Gallery.opened = true;
				
		} else {
			
			new Preloader(fullUrl, {

				'onComplete'	: function() { 

					var html = [];

					html.push('<div class="overlay-inner">');

					html.push('<div class="overlay-header">');
					html.push('<h4>' + Gallery.title + '<span class="close" onclick="Gallery.overlay.close();">x</span></h4>');
					html.push('</div>');

					html.push('<div class="overlay-body clr">');

					html.push('<div id="overlay-image">')
					html.push('<img onclick="Gallery.selectOverlayImage(1);" src="' + fullUrl + '"/>');
					html.push('</div>');
				
					if(Gallery.images.length > 1) {
					
						html.push('<a href="javascript:void(0);" class="previous" onclick="Gallery.selectOverlayImage(-1);">Previous</a>');
						html.push('<a href="javascript:void(0);" class="next" onclick="Gallery.selectOverlayImage(1);">Next</a>');
					}
				
					html.push('</div>');	
					html.push('</div>');

					Gallery.overlay.open(html.join(''));
					Gallery.overlay.element.setStyle('z-index', '99999999');
					Gallery.overlay.pos();
				
					Gallery.opened = true;
				}
			});
		}
	},
	
	selectOverlayImage : function(direction) { // -1 left 1 right
		
		var newImg;
		
		if(direction == -1 && this.overlayAct == 0)
			newImg = this.images.length - 1;
		else if(direction == 1 && this.overlayAct == this.images.length - 1)
			newImg = 0;
		else if(direction == 1)
			newImg = this.overlayAct + 1;
		else
			newImg = this.overlayAct - 1;
		
		var img = this.images[newImg];
		
		if(img.getProperty('data-code') && img.getProperty('data-code') != "") {
			
			$('overlay-image').setHTML('<iframe width="600" height="400" src="http://www.youtube.com/embed/' + img.getProperty('data-code') + '" frameborder="0" allowfullscreen></iframe>');
			Gallery.overlay.pos.delay(10, Gallery.overlay);

		} else {
			
			var fullUrl		= img.getProperty('data-fullsrc');
		
			new Preloader(fullUrl, {

				'onComplete'	: function() { 
					
					$('overlay-image').setHTML('<img onclick="Gallery.selectOverlayImage(1);" src="' + img.getProperty('data-fullsrc') + '"/>');
					Gallery.overlay.pos.delay(10, Gallery.overlay);
				}
			});
		}
		
		this.overlayAct = newImg;
		this.overlay.pos.delay(500, this.overlay);
	},
	
	selectImage : function(dot, force) {
	
		if(this.animating)
			return;
			
		if(!dot)
			return;
			
		if(dot.hasClass('active'))
			return;
			
		var index 		= parseInt(dot.getProperty('data-dot'));	
		var activeImg 	= this.images[this.active];
		var newImg		= this.images[index];
		
		// fade out the active
		new Fx.Style(activeImg, 'opacity', { 

			'duration' : 300,
			'onComplete' : function() {

				// fade in the new		
				new Fx.Style(newImg, 'opacity', { 
		
					'duration' 		: 300,
					'onComplete'	: function() { Gallery.animating = false; }
		
				}).start(0, 1);
			} 

		}).start(1, 0);
		
		// remove the old active
		this.dots.each(function() { this.removeClass('active'); });
		
		// set the dot as active
		dot.addClass('active');
		
		// update the active index
		this.active 		= index;
		this.overlayAct		= index;
		
		if(!force)
			this.timerId = this.getNext.delay(this.interval, this);
	},
	
	getNext : function() {
		
		if(this.animating || !this.dots)
			return;
			
		var newIndex = 0;
		
		if(this.active == this.dots.length - 1)
			newIndex = 0;
		else
			newIndex = this.active + 1;
			
		var dot = this.dots[newIndex];
		
		this.selectImage(dot);
	}
}

Adult = {
	
	initialize 	: function() {
		
		// REMOVE 0
		if(Cookie.get('bestprice.adult'))
			return false;
	
		this.imgs 		= [];
		this.covers 	= [];
		this.duration 	= 1000;

		var self = this;
		
		// Adult movies // Adult gifts
		$$('td[data-cid="772"], td[data-cid="5605"], .redirect-box .product[data-cid="772"], .redirect-box .product[data-cid="772"]').each(function(td) {
			
			var img = td.getElement('img');
			
			!img.src.contains('no-image') && self.imgs.push(td.getElement('img').setOpacity(.02));
		});
		
		this.imgs.each(this.cover);
		$('trail') && this.imgs.length && this.warn();
		
		return this;
	},
	
	warn		: function() {
	
		$C('p').
		setStyles({
			'background' 	: '#f9f9f9',
			'padding'		: '10px'
		}).
		setClass('suggestion suggestion-red suggestion-adult').
		injectBefore($('trail')).
		setHTML('Τα αποτελέσματα αναζήτησης που περιέχονται σε αυτή τη σελίδα πιθανόν περιέχουν εικόνες<br/>ακατάλληλες για ανηλίκους <a style="margin-left:0; position: absolute; right: 10px; top: 13px;" href="javascript:void(0);" class="button" onclick="Adult.reveal(this);">Εμφάνιση εικόνων</a>');
	},
	
	cover		: function(img) {
		
		var parent = img.getParent().getParent().makePositioned();
		var cover = $C('div',{
			styles : {
				'width'				: img.width,
				'height'			: img.height,
				'position'			: 'absolute',
				'top'				: img.offsetTop,
				'left'				: img.offsetLeft,
				'opacity'			: 1.0
			}
		}).setClass('parental').injectIn(parent);
		
		Adult.covers.push(cover);
	},
	
	reveal		: function(element) {
		
		if(!window.confirm('Είμαι μεγαλύτερος από 18 ετών και συναινώ στην προβολή του περιεχομένου της σελίδας.'))
			return false;
		
		alert('Η προηγούμενη ειδοποίηση δεν θα εμφανίζεται πλέον κατά την πλοήγησή σου στο Bestprice.');
		
		$(element).getParent().effect('opacity',{
			
			'duration'		: Adult.duration,
			'onComplete' 	: function() {
				
				$(element).getParent().remove();				
			}
			
		}).start( 0 );

		Cookie.set('bestprice.adult', 1);
		
		this.covers.each(function(cover) {
			cover.effect('opacity',{
				duration: Adult.duration
			}).start( 0 );
		});

		this.imgs.each(function(img) {
			img.effect('opacity',{
				duration: Adult.duration
			}).start( 1 );
		});
	}
}


window.Tip && Tip.setOptions({
	onSelect : function(element) { 
		element._title = element._title || element.getProperty('title');
		this.setContent(element._title); }
});

Tips = {
	
	initialize : function() {

		if($('prices')) {
			
			this.html =  '<p><strong>Γιατί αυτή η λέξη έχει διαφορετικό στυλ παρουσίασης;</strong></p>';
			this.html += '<br/>';
			this.html += '<p>Το BestPrice επισημαίνει τα σημεία του τίτλου κάθε προϊόντος που διαφοροποιούνται σε σχέση με τον βασικό τίτλο.</p>';
			this.html += '<br/>';
			this.html += '<p>Με αυτόν τον τρόπο μπορείς να εντοπίζεις πιο εύκολα τις διαφορές από μαγαζί σε μαγαζί.<p>';

			new Tip('#prices .descr a i', { 'className' : 'popuptip' }).setContent(this.html);
		}
		
		new Tip('.popup-tip', 				{ 'className' : 'popuptip' });
		new Tip('#wrapper .micons .icon', 	{ 'className' : 'popuptip' });
	}
}

ReadTerms = {
	
	initialize : function() {
		
		if(!$('read-terms'))
			return;
		
		if(!returnTerms)
			return;	

		this.overlay = new Overlay('', {
			'duration'		: 400,
			'className'		: 'overlay',
			'onOpen'	: function() {

				this.element.addClass('overlay-normal');
			},
			'beforeClose': function() {

				this.element.removeClass('overlay-normal');
			}
        });

		this.returnTerms = returnTerms;
		
		$('read-terms').addEvent('click', this.render.bind(this));
	},
	
	render : function() {
		
		var html = [];

		html.push('<div class="overlay-inner">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Όροι επιστροφής προϊόντων<span class="close" onclick="ReadTerms.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body clr">');

		html.push('<div class="terms">');
		html.push(this.returnTerms);
		html.push('</div>');
	
		html.push('<p><a class="button" href="javascript:void(0);" onclick="ReadTerms.overlay.close();">κλείσιμο</a></p>');
		
		html.push('</div>');	
		html.push('</div>');

		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();
	}
}

ProductsExpander = {
	
	initialize : function() {
		
		if(!$('prices'))
			return;
		
		this.elements = $('prices').getElements('tr');
		
		if(this.elements.length == 0)
			return;
			
		var previousElement = this.elements[0];
		
		this.elements.each(function() {
			
			if(this.isHidden()) {
				
				var m 			= $(this).getProperty('data-m');
				var isLast		= $(this).hasClass('bottom');
				
				//attach an expander into the previous tr
				ProductsExpander.attachExpander(previousElement, m, isLast);
				
			} else
				previousElement = this;
		});
	},
	
	attachExpander : function(hostElement, merchantId, isLast) {
		
		// Check if there's already an expander attached
		if($(hostElement).getElement('.expander'))
			return;
			
		if(isLast)
			$('prices').addClass('last-expander');
		
		var thumbElements 		= ($(hostElement).getElement('.thumb') ? $(hostElement).getElement('.thumb').childNodes : []);
		var thumbElementsLength	= parseInt(thumbElements.length);
		
		var container = $C('div').setStyles({
							'position' 	: 'relative',
							'width'		: '0',
							'height'	: '0',
							'top'		: '0',
							'left'		: '0'
						});
					
		if(thumbElementsLength == 0)
			container.injectIn(($(hostElement).getElement('.thumb') ? $(hostElement).getElement('.thumb') : $(hostElement).getElement('.descr')));
		else
			container.injectBefore(thumbElements[0]);
		
		var height 	= '';
		var	top		= '';
		
		if($('item').hasClass('book')) {
			
			top = '-28px';
			
			if(window.gecko) {
				
				top = '-27px';
				height = '71px';
				
			} else if(window.ie8 || window.ie7) {
				
				top	= '-27px';
				height 	= '72px';
				
			} else
				height = '73px';
			
		} else if((!window.ie8 && !window.ie7 && thumbElementsLength - 1 == 0) || ((window.ie8 || window.ie7) && thumbElementsLength == 0)) {
		
			top = '-27px';
			
			if(window.gecko)
				height = '51px';
			else if(window.ie8 || window.ie7)
				height 	= '52px';
			else
				height = '53px';				
			
		} else {

			top = '-11px';
			
			if(window.gecko)
				height = '84px';
			else
				height = '83px';
		}

		if(window.ie) 
			$(hostElement).setBlockStyles();

		height 	= $(hostElement).offsetHeight - 1;

		if(window.ie)
			$(hostElement).restoreBlockStyles();
			
		$C('div')
			.setClass('expander')
			.setHTML('▶')
			.setStyles({
				'height' 		: height,
				'line-height'	: height,
				'top'			: top
			})
			.injectIn(container)
			.addEvent('click', function() {
				
				var opened = false;
				
				if($(this).innerHTML == "▼")
					opened = true;
					
				$(this).setHTML((!opened ? "▼" : "▶"));
			
				if(isLast)
					$('prices').toggleClass('last-expander');
					
				$('prices')
						.getElements('tr[data-m="' + merchantId + '"].secondary')
						.setStyle('display', (!opened ? (window.ie7 ? 'block' : 'table-row') : 'none'));
				
			}).makeUnselectable();
	},
	
	collapseAll : function() {
		
		$('prices').getElements('.expander').setHTML('▶');
		$('prices').getElements('.secondary').hide();
	}
}

PageIframe = {
	
	initialize : function() {
		
		if(!$('page-iframe'))
			return;
		
		this.iframe = $('page-iframe').getElement('iframe');
		
		this.resize();
		
		window.addEvent("resize", this.resize.bind(this));
	},
	
	resize : function() {
		
		var height = window.getHeight();
		
		this.iframe.setStyle('height', (height - 50) + 'px');
	}
}

WelcomeBox = {
	
	initialize : function() {
		
		if(!$('welcome-box'))
			return;
			
		this.box = $('welcome-box');
		
		this.box.setStyle('height', 0);
		
		var fx = new Fx.Style(this.box, 'height', { 
			'duration' 		: 300,
			'onComplete'	: function() { window.invokeEvent('reflow'); }
		});
		
		fx.start.delay(1000, fx, '0px', '34px');
		
		this.box.getElement('a.close').addEvent('click', function() {

			var fx = new Fx.Style(WelcomeBox.box, 'height', { 
				'duration' 		: 300,
				'onComplete'	: function() { WelcomeBox.box.remove(); }
			});
			
			fx.start('34px', '0px');
			
			Cookie.set('hide-welcome', '1', { 'duration' : 100 });
		});	
	}
}

CategorySearch = {

	initialize : function() {
		
		if(!$('category-search'))
			return;

		this.checked 	= false;			
		this.element 	= $('category-search');
		this.searchBox	= $('search-box');
		this.id			= parseInt(this.element.getProperty('data-cat'));

		if(this.element.hasClass('checked')) {
			this.checked = true;
		}
			
		// Set to mousedown in order to avoid
		// loosing focus.	
		this.element.addEvent('mousedown', this.toggleActive.bind(this));
	},

	toggleActive : function(event) {
		event && event.stop();
		if(this.checked) {
			
			$('search-cat') && $('search-cat').remove();
			$('search-cat-in') && $('search-cat-in').remove();
			
			this.searchBox.value = this.searchBox.value + ''; 
			
			if(this.searchBox.selectionStart !== undefined)
				this.searchBox.selectionStart = this.searchBox.selectionEnd = this.searchBox.value.length;
			
		} else {

			!$('search-cat') && $C('input', {
				'type' 	: 'hidden',
				'name'	: 'c',
				'id'	: 'search-cat',
				'value' : this.id
			}).injectAfter(this.element);

			!$('search-cat-in') && $C('input', {
				'type' 	: 'hidden',
				'name'	: 'inCat',
				'id'	: 'search-cat-in',
				'value' : 1
			}).injectAfter(this.element);

			this.searchBox.focus();
			this.searchBox.select();
		}

		this.element.toggleClass('checked');
		$('overlay-category-search').toggleClass('checked');
		
		this.checked = !this.checked;
	}
}

Filters = {
	
	initialize : function() {
		
		if(!$('filters'))
			return;
			
		$('filters').getElements('li h5').addEvent('click', function() { Filters.toggleFilterShow(this.getParent(), this); });
		$('filters').getElements('p.more').addEvent('click', function() { Filters.toggleHiddenElements(this.getParent(), this); });
	},
	
	toggleHiddenElements : function(filterList, moreElement) {
	
		var hiddenElements 	= $(filterList).hiddenElements || $(filterList).getElements('li[style]');
		var showIt			= (typeof $(filterList).showIt == 'boolean' ? $(filterList).showIt : true);
		
		hiddenElements.each(function() { 
		
			if(showIt)
				this.show(); 
			else
				this.hide();
		});			
		
		$(filterList).showIt = !showIt;
		
		if(showIt)
			$(moreElement).addClass('less').setHTML('<a href="javascript:void(0);">Λιγότερα</a>');
		else
			$(moreElement).removeClass('less').setHTML('<a href="javascript:void(0);">Περισσότερα</a>');
	},
	
	toggleFilterShow : function(filterElement, headerElement) {

		if(filterElement.loading)
			return;
			
		var em 		= $(headerElement).getElement('em');
		var filter	= $(headerElement).getParent().getParent();
		
		if(!em)
			return;

		filterElement.loading = true;
		
		var filterValues = ($(filterElement).getElement('.filter-container') ? $(filterElement).getElement('.filter-container') : $(filterElement).getElement('ul'));

		if(filterValues.isHidden()) {

			filterValues.setStyle('opacity', 0);
			filterValues.show();
			
			new Fx.Style(filterValues, 'opacity', { 
				'duration' 		: 200,
				'onComplete'	: function() { 
					
					filterElement.loading = false; 
					$(em) && em.setHTML('-');
					filter.addClass('opened');
				}
				
			}).start(0, 1);

		} else {

			new Fx.Style(filterValues, 'opacity', { 
				'duration' 		: 200,
				'onComplete'	: function() {

					filterValues.hide();
					filterValues.setStyle('opacity', 1);
					filterElement.loading = false;
					$(em) && em.setHTML('+');
					filter.removeClass('opened');
				}
			}).start(1, 0);
		}
	}
}

CloseSuggestion = {

	initialize : function() {
		
		if(!$('close-suggestion'))
			return;
			
		$('close-suggestion').addEvent('click', function() {
			
			var suggestion = $(this).getParent();
			
			new Fx.Style(suggestion, 'opacity', { 
				'duration' 		: 300,
				'onComplete'	: function() { $(suggestion).remove(); }
			}).start(1, 0);
		});
	}
}

MoreSecondaryCats = {
	
	initialize : function() {
		
		if(!$('main-results-container'))
			return;
		
		$('main-results-container').getElements('.more-subcats').addEvent('click', function() { MoreSecondaryCats.toggleMoreCats(this); });
	},
	
	toggleMoreCats : function(moreElement) {
		
		var list = $(moreElement).getParent().getParent().getElements('li[style]');
		
		list.each(function() {
		
			this.toggle();
		});
	
		$(moreElement).remove();
	}
}

CustomPriceFilter = {

	submitForm : function(form, customField) {
		
		var minEl 	= $((form.cmin ? form.cmin : form.min));
		var maxEl 	= $((form.cmax ? form.cmax : form.max));
		var min		= 0;
		var max 	= 0;
		var toSubmit= false;
		var localMax= parseInt($(form).getProperty('data-max'));

		if(minEl.getValue() == "" && maxEl.getValue() == "") {
			
			minEl.focus();
			return false;
		}
		
		if(minEl.getValue() != "") {
		
			min	= parseFloat(minEl.getValue().replace(/,/gi, '.'));

			if(!isNaN(min))
				toSubmit = true;
		}
		
		if(maxEl.getValue() != "") {
			
			max	= parseFloat(maxEl.getValue().replace(/,/gi, '.'));
		
			if(!isNaN(max))
				toSubmit = true;
		}

		if(minEl.getValue() != "" && maxEl.getValue() != "" && min > max) {
			
			minEl.focus();
			return false;
		}
		
		// if(minEl.getValue() != "" && min > localMax) {
			
		// 	minEl.focus();
		// 	return false;
		// }
		
		if(toSubmit) {
				
			if(typeof customField != 'undefined')
				$(form).getElement('input[name="' + customField + '"]').setValue((min * 1000) + '-' + (max * 1000));

			var filters = [];

			form.getElements('input').each(function() {
				
				if(this.name == '')
					return;

				var value = this.value;

				if(this.name == 'cmin' || this.name == 'cmax')
					return;

				if(typeof customField == 'undefined' && (this.name == 'min' || this.name == 'max'))
					value *= 100;
				
				filters.push(this.name + '=' + value);
			});

			window.location = window.location.pathname + '?' + filters.join('&');
		}

		return false;
	}
}

ScrollItem = {
	
	initialize : function() {

		if(!$('page-item'))
			return;
		
		if(window.ios)
			return;
			
		if(window.screen.height < 800)
			return;

		this.hideFixed 		= false;
		this.isAnimating 	= false;

		this.element = $('item-summary-bar');
		
		if(!window.hasEvent('scroll')) {
			
			window.addEvent('scroll', function(event) {

				if(ScrollItem.isAnimating)
					return;
				
				var scrollTop = window.getScrollTop();		

				if(scrollTop >= 400 && !ScrollItem.element.isVisible()) {
				
					ScrollItem.element.show();
					ScrollItem.isAnimating = true;
					
					new Fx.Style(ScrollItem.element, 'top', { 

						'duration' : 300,
						'onComplete' : function() { ScrollItem.isAnimating = false; } 

					}).start(-125, 0);
				
				} else if(scrollTop < 400 && ScrollItem.element.isVisible()) {
					
					ScrollItem.isAnimating = true;
					
					new Fx.Style(ScrollItem.element, 'top', { 

						'duration' : 300,
						'onComplete' : function() { 
						
							ScrollItem.element.hide();
							ScrollItem.isAnimating = false; 
						}

					}).start(0, -125);
				}
			});
		}	
	},

	hide : function() {

		if(this.element.isHidden())
			return;

		this.element.hide();
	},

	reset 		: function(onRemove) {
		this.hideFixed	 = true;
		this.element && this.element.removeClass('fixed');

		return this;
	}
}

Texter 		= {

	expand 		: function(element) {
	
		var p 		= element.getParent();
		var dots 	= element.getPrevious();
		var content = element.getNext();

		dots.remove();
		element.remove();
		content.addClass('texter-content-expanded');
	}
}

MyLocation 	= {
	
	initialize : function() {
		
		if(!$('my-location'))
			return;
		
        this.overlay = new Overlay('', {
			'duration'		: 400,
			'className'		: 'overlay',
			'onOpen'		: function() { this.element.addClass('overlay-normal'); },
			'beforeClose'	: function() { this.element.removeClass('overlay-normal'); }
        });

		document.domain = 'bestprice.gr';
		
		this.setupIframe();
		
		$('my-location').addEvent('click', this.render.bind(this));
	},
	
	render : function() {
		
		if($('nearby'))
			this.setupIframe();
			
		var html = [];

		html.push('<div class="overlay-inner">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Ορισμός διεύθυνσης<span class="close" onclick="MyLocation.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body clr" id="geopicker-container">');
		html.push('</div>');	
		
		html.push('</div>');

		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();
		
		if(this.geopicker.iframe)
			this.geopicker.iframe.injectIn($('geopicker-container'));
		else
			this.geopicker.write($('geopicker-container'));
	},
	
	updateNonLoggedInLocation : function(locationObject, save) {

		userLat = locationObject.lat;
		userLon = locationObject.lon;
	
		this.overlay && this.overlay.close();

		if(typeof(localStorage) != 'undefined' && save === true)
			localStorage['userlatlon'] = JSON.stringify({'lat' : locationObject.lat, 'lon' : locationObject.lon, 'address' : locationObject.address});

		Nearby.mylocation.setHTML('(<span class=\"small-myloc\">Badge</span>' + locationObject.address + ')');
		Nearby.locationLegend.setHTML('Αλλαγή διεύθυνσης &raquo;');
		Nearby.getStores();	
	},

	setupIframe : function() {
		
		this.geopicker = new GeoPicker.User({

			'iframeURI'		: '/Geo/iframe.php',
		    'width' 		: '580',
		    'height'		: '500',
		    'button'		: 'false',
			'location'		: {
				'lat'	: (typeof userLat != 'undefined' && !isNaN(userLat) ? userLat : 37.9711246),
				'lon'	: (typeof userLon != 'undefined' && !isNaN(userLon) ? userLon : 23.7253504)
			},
			'saveOnMembers' : false,
			'ignoreLoad'	: true,
			'bubble'		: true,
			'noStyles' 		: true,

			'onSaving' : function() {
				
				if($('nearby') && typeof window.User.ak == 'undefined') {
					
					MyLocation.updateNonLoggedInLocation(this.location, true);

					// var object = this.location;

					// userLat = object.lat;
					// userLon = object.lon;
				
					// MyLocation.overlay.close();
					// Nearby.mylocation.setHTML('(<span class=\"small-myloc\">Badge</span>' + object.address + ')');
					// Nearby.locationLegend.setHTML('Αλλαγή διεύθυνσης &raquo;');
					// Nearby.getStores();	

					// if (typeof(localStorage) == 'undefined')
					// 	return;

					// localStorage['userlatlon'] = JSON.stringify({'lat' : object.lat, 'lon' : object.lon, 'address' : object.address});
				}
			},
			
		    'onSave' : function(object) { 

				if($('nearby') && typeof window.User.ak == 'undefined')
					return;

				var parameters = {
					'action' 		: 'saveUserLocation',
					'ak'			: window.User.ak,
					'isAjax'		: true,
					'lat'			: object.lat,
					'lon'			: object.lon
				};
				
				new Ajax('post', {

					'encoding' : 'utf-8',

					onSuccess : function()	{

						var response = this.responseJSON;

						if(response.res.faultCode && parseInt(response.res.faultCode) == 403) {
							
							MyLocation.overlay.close();
							LoginRegisterBox.loginRender(response.res.fwd, true);
							
						} else if($('nearby')) {
							
							userLat = object.lat;
							userLon = object.lon;
							
							MyLocation.overlay.close();
							Nearby.mylocation.setHTML('(<span class=\"small-myloc\">Badge</span>' + object.address + ')');
							Nearby.locationLegend.setHTML('Αλλαγή διεύθυνσης &raquo;');
							Nearby.getStores();
							
						} else if(response.res)
							window.location.reload();
					},

					'parameters' : parameters

				}).send();
		    }
		});
	}
}

PriceDrop = {
	
	initialize : function() {
		
		this.elements = $('wrapper').getElements('.price .drop');
		
		if(this.elements.length == 0)
			return;
			
		this.elements.addEvents({
				
			'mouseenter' : function() {
		
				this.percent 	= this.percent || parseInt(this.innerHTML);
				this.price		= this.price || (parseInt(this.getParent().getElement('a').innerHTML.stripTags().replace(/\./, '')) / 100);
				this.width		= this.width || parseInt(this.getStyle('width'));
				
				var oldPrice 	= 100 * this.price / (100 + this.percent);
				var diff		= parseInt(oldPrice - this.price);
				
				this.setHTML('-' + diff + '&euro;');
				
				this.newWidth = this.newWidth || parseInt(this.getStyle('width'));
				
				$(this).setStyle('width', this.width + 'px');
				
				this.fx = this.fx || this.effects({ 'duration' : 100 });
				
				this.fx.start({
					'width' 			: [this.width, this.newWidth],
					'background-color'	: ['#008000', '#6f6f6f']
				});
			},
			
			'mouseleave' : function() {	
			
				this.setHTML(this.percent + '%'); 
				$(this).setStyle('width', this.newWidth + 'px');

				this.fx.start({
					'width' 			: [this.newWidth, this.width],
					'background-color'	: ['#6f6f6f', '#008000']
				});
			}
		});		
	}
}

WantHave = {

	'documentEvent' : false,

	initialize : function() {
		
		if(!$('have-want-container'))
			return;

		this.loading = false;
				
		this.setupOverlay();

		this.pid			= parseInt($('have-want-container').getProperty('data-pid'));
		this.wantButton 	= $('have-want-container').getElement('.want');
		this.haveButton 	= $('have-want-container').getElement('.have');
		this.hasReviewed	= ($('reviews').getProperty('data-hasreviewed') == 1);
		this.haveEl			= $('have-cnt');
		this.haveCnt		= parseInt(this.haveEl.innerHTML);
		this.wantEl			= $('want-cnt');
		this.wantCnt		= parseInt(this.wantEl.innerHTML);
		this.recommendEl	= $('recommend-cnt');
		this.recommendCnt	= (this.recommendEl ? parseInt(this.recommendEl.innerHTML) : 0);
		this.userRecommends = (this.recommendEl ? this.recommendEl.getProperty('data-recommend') == 1 : false);
		
		this.wantButton.addEvent('click', this.toggleWant.bind(this));	
		this.haveButton.addEvent('click', this.toggleHave.bind(this));
		
		if(!this.documentEvent) {
				
			document.addEvent('keyup', function(event) { 
				
				if(event.code == 27) {
					
					$('want-popup') && $('want-popup').remove();
					$('have-popup') && $('have-popup').remove();
				}
			});
		}
	},
	
	setupOverlay : function() {
	
        this.overlay = new Overlay('', {
			'duration'		: 400,
			'className'		: 'overlay',
			'onOpen'		: function() { this.element.addClass('overlay-normal'); },
			'beforeClose'	: function() { this.element.removeClass('overlay-normal'); }
        });
	},

	toggleWant : function() {

		var active = this.wantButton.hasClass('active');
		
		// make the call
		this.ajaxCall('toggleWishList', !active, function(response) {
			
			$('have-popup') && $('have-popup').remove();
			$('want-popup') && $('want-popup').remove();
			
			// on success make the button active
			if(!active) {

				if(WantHave.haveButton.hasClass('active'))
					WantHave.haveCnt--;
					
				WantHave.wantButton.addClass('active');
				WantHave.haveButton.removeClass('active');
				
				var html = [];

				html.push('<h6>Προστέθηκε στη λίστα!<span class="close" onclick="$(\'want-popup\').remove();">×</span></h6>');
				html.push('<p><a href="/user/#wishlist">Δες την λίστα</a> των προϊόντων που θέλεις</p>');
				
				// only for the santa thing
				if($('have-want-container').getElement('.santa-stars'))
					html.push('<p>Αυτό ήταν, μόλις μπήκες στην κλήρωση! Μπορεί να είσαι ένας από τους 3 τυχερούς που θα κερδίσουν δώρα από τη λίστα τους αξίας έως και 1.000€.</p>');

				if(response && response.res && response.res.noAuto)
					html.push('<p>Κάνε κλικ <a href="/user/#oauth">εδώ</a> για να ενεργοποιήσεις την αυτόματη δημοσίευση.</p>');
					
				$C('div', { 'id' : 'want-popup' }).setClass('contextual').setHTML(html.join('')).injectIn($('have-want-container'));

				WantHave.wantCnt++;
				
				if(WantHave.userRecommends)
					WantHave.recommendCnt--;
					
			} else {
				
				WantHave.wantButton.removeClass('active');
				WantHave.wantCnt--;
			}
			
			WantHave.refreshCounts();
		});
	},
	
	refreshCounts : function() { 
	
		if(!this.haveEl || !this.wantEl)
			return;

		this.haveEl.setHTML(this.haveCnt);
		this.wantEl.setHTML(this.wantCnt);
		
		if(this.recommendCnt == 0 && this.recommendEl) {
			
			this.recommendEl.getParent().remove();
			this.recommendEl = null;
			
		} else if(!this.recommendEl && this.recommendCnt > 0) {
			
			$C('p').setClass('recommend').setHTML('<em id=\"recommend-cnt\">' + this.recommendCnt + '</em> από όσους το έχουν το προτείνουν').injectAfter($('have-want-container'));
			
			this.recommendEl 		= $('recommend-cnt');
			this.userRecommends		= true;
			
		} else if(this.recommendEl)
			this.recommendEl.setHTML(this.recommendCnt);
	},
	
	toggleHave : function() {

		var active = this.haveButton.hasClass('active');
		
		// make the call
		this.ajaxCall('toggleHaveList', !active, function(response) {
			
			$('have-popup') && $('have-popup').remove();
			$('want-popup') && $('want-popup').remove();
			
			// on success make the button active
			if(!active) {

				if(WantHave.wantButton.hasClass('active'))
					WantHave.wantCnt--;
					
				WantHave.haveButton.addClass('active');
				WantHave.wantButton.removeClass('active');
			
				var html = [];

				html.push('<h6>Προστέθηκε στη λίστα!<span class="close" onclick="$(\'have-popup\').remove();">×</span></h6>');
				html.push('<p><a href="/user/#havelist">Δες την λίστα</a> των προϊόντων που έχεις.</p>');

				if(response && response.res && response.res.noAuto)
					html.push('<p>Κάνε κλικ <a href="/user/#oauth">εδώ</a> για να ενεργοποιήσεις την αυτόματη δημοσίευση.</p>');
					
				$C('div', { 'id' : 'have-popup' }).setClass('contextual').setHTML(html.join('')).injectIn($('have-want-container'));
				
				WantHave.haveCnt++;
				
				// display an overlay for recommend + rating
				WantHave.renderRate();

			} else {
				
				WantHave.haveButton.removeClass('active');			
				WantHave.haveCnt--;
				
				if(WantHave.userRecommends)
					WantHave.recommendCnt--;
			}
			
			WantHave.refreshCounts();
		});
	},

	isHelpful : function() {

		// Send the is Helpful request here
		this.ajaxCall('recommendProduct', true, function(response) {

			// proceed on success
			WantHave.renderReview();
			
			WantHave.recommendCnt++;
			WantHave.refreshCounts();
		});
	},
	
	ajaxCall : function(method, status, fn) {
		
		if(this.loading)
			return;
			
		this.loading = true;
		
		var parameters = {
			'action' 		: method,
			'status'		: (status ? 1 : 0),
			'productId'		: this.pid,
			'ak'			: window.User.ak,
			'isAjax'		: true
		};
		
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				WantHave.loading = false;
				
				var response = this.responseJSON;

				if(parseInt(response.res.faultCode) > 0) {
				
					if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else
						alert('Σφάλμα: ' + response.res.faultString);

					return;					
				}

				fn(response);
			},
		
			'parameters' : parameters
		
		}).send();
	},
	
	renderRate : function() {
		
		var html = [];

		html.push('<div class="overlay-inner">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Αξιολόγηση προϊόντος ' + (!this.hasReviewed ? '(1/2)' : '') + '<span class="close" onclick="WantHave.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body clr rate-product">');
		html.push('<p class="question">Θα πρότεινες αυτό το προϊόν και στους υπόλοιπους χρήστες του Bestprice;</p>');
		
		html.push('<p class="choices">');
		html.push('<a href="javascript:void(0);" onclick="WantHave.isHelpful();" class="button yes">Ναι</a>');
		html.push('<a href="javascript:void(0);" onclick="WantHave.renderReview();" class="button no">Όχι</a>');
		html.push('</p>');
		
		if(!this.hasReviewed)
			html.push('<p class="skip"><a href="javascript:void(0);" onclick="WantHave.renderReview();">Παράλειψη αυτού του βήματος &raquo;</a></p>');
			
		html.push('</div>');	
		html.push('</div>');
		
		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();		
	},
	
	renderReview : function() {
		
		if(this.hasReviewed) {
			
			this.overlay.close();
			return;
		}
		
		var html = [];
		
		html.push('<div class="overlay-inner">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Αξιολόγηση προϊόντος (2/2)<span class="close" onclick="WantHave.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body clr rate-product">');
		html.push('<p class="question">Θέλεις να αφήσεις την αξιολόγησή σου για αυτό το προϊόν;</p>');
		
		html.push('<p class="choices">');
		html.push('<a href="javascript:void(0);" class="button yes" onclick="WantHave.reviewIt();">Ναι</a>');
		html.push('<a href="javascript:void(0);" class="button no" onclick="WantHave.overlay.close();">Όχι</a>');
		html.push('</p>');
		
		html.push('</div>');	
		html.push('</div>');
		
		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();
	},

	reviewIt : function() {
		
		if($('page-user')) {
			
			location = '/item/' + this.pid + '#item-reviews';

		} else {

			WantHave.overlay.close();
			ReviewIt.open();
		}
	}
}

ItemRating = {

	initialize : function() {
		
		if(!$('item-rating'))
			return;
			
		if(window.User.id == 0) {
			
			$('item-rating').getElements('em').addEvent('click', function() {
				LoginRegisterBox.loginRender(undefined, true);
			});
			
			return;
		}

		this.itemRating 	= 0;
		this.userRating 	= 0;
		this.loading 		= false;

		this.originalText 	= $('item-rating').getElement('span');
		this.itemRating		= $('item-rating').getElements('em.hi').length;
		
		$('item-rating').getElements('em').addEvent('mouseenter', function() {

			var id = parseInt($(this).id.split(/star-/)[1]);

			ItemRating.updateStars(id);
		});

		$('item-rating').getElements('em').addEvent('mouseover', function() {

			var id = parseInt($(this).id.split(/star-/)[1]);

			ItemRating.updateStars(id);
		});

		$('item-rating').addEvent('mouseleave', function() { ItemRating.updateStars(ItemRating.userRating); });

		$('item-rating').getElements('em').addEvent('click', function() {

			var id = parseInt($(this).id.split(/star-/)[1]);

			ItemRating.saveRating(id);
		});
	},
	
	updateStars : function(id) {
		
		var score = (id == 0 ? this.itemRating : id);
		
		for(var i = 1; i <= 5; i++) {

			var el = $('top-review-star-' + i);

			if(i <= score)
				$(el).setClass((this.userRating > 0 || id > 0? 'my-hi' : 'hi'));
			else {
				$(el).removeClass('my-hi');
				$(el).removeClass('hi');
			}
		}
		
		var text = '';
		
		if(id == 1)
			text = 'Απαίσιο';
		else if(id == 2)
			text = 'Κακό';
		else if(id == 3)
			text = 'Μέτριο';
		else if(id == 4)
			text = 'Καλό';
		else if(id == 5)
			text = 'Φοβερό';

		$('item-rating').getElements('a,span').each(function() { this.remove(); });
		
		if(id > 0)		
			$C('span').setHTML(text).injectIn($('item-rating'));
		else
			this.originalText.injectIn($('item-rating'));
	},
	
	saveRating : function(value) {
		
		if(this.loading)
			return;
			
		this.loading 	= true;
		this.userRating = value;
		
		var parameters = {
			'action' 		: 'submitItemReview',
			'review-stars'	: this.userRating,
			'ak'			: window.User.ak,
			'isAjax'		: true
		};
		
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				ItemRating.loading = false;
				
				var response = this.responseJSON;

				if(parseInt(response.res.faultCode) > 0) {
				
					if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else
						alert('Σφάλμα: ' + response.res.faultString);

					return;
				}

				$('item-rating').getElement('a') && $('item-rating').getElement('a').remove();
			},
		
			'parameters' : parameters
		
		}).send();
	}
}

Wishlist = {

	initialize : function() {
		
		if(!$('wishlist'))
			return;

		this.loading 	= false;			
		this.elements 	= $('wishlist').getElements('.removeit');
		this.haveIt		= $('wishlist').getElements('.haveit');
		this.tr			= $('wishlist').getElements('tr');
		
		if(this.elements.length == 0)
			return;
			
		this.haveIt.addEvent('click', function() { Wishlist.removeProduct(this, 1); });
		this.elements.addEvent('click', function() { Wishlist.removeProduct(this); });
	},
	
	removeProduct : function(element, have) {
		
		if(this.loading)
			return;
		
		this.loading = true;
		
		var pid 		= $(element).getProperty('data-pid');
		var parameters 	= {};
		
		if(have == 1) {
		
			parameters = {
				'action' 		: 'toggleHaveList',
				'status'		: 1,
				'productId'		: pid,
				'ak'			: window.User.ak,
				'isAjax'		: true
			};
			
		} else {
			
			parameters = {
				'action' 		: 'toggleWishList',
				'status'		: 0,
				'productId'		: pid,
				'ak'			: window.User.ak,
				'isAjax'		: true
			};
		}
		
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				Wishlist.loading = false;
				
				if(parseInt(response.res.faultCode) > 0) {
				
					if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else
						alert('Σφάλμα: ' + response.res.faultString);
										
					return;
					
				}

				if(have == 1) {
					
					WantHave.pid = pid;
					WantHave.setupOverlay();
					WantHave.renderRate();
				}

				Wishlist.deleteItem(pid);
			},
		
			'parameters' : parameters
		
		}).send();
	},
	
	deleteItem : function(pid) {
		
		var item = $('pid-' + pid);

		if(item.hasClass('last') && Wishlist.tr.length > 1)
			Wishlist.tr[Wishlist.tr.length - 2].addClass('last');

		item.remove();

		Wishlist.tr	= $('wishlist').getElements('tr');
		$('tab-wishlist').setHTML('<em>&nbsp;</em>Προϊόντα<span>που θέλω (' + Wishlist.tr.length + ')</span>');
		
		if(Wishlist.tr.length == 0)
			$('wishlist').getElement('.body').setHTML('<div class="pale"><div class="text"><p>Δεν έχεις προσθέσει ακόμη προϊόντα σε αυτή την λίστα</p><p class="sub">Για να προσθέσεις προϊόντα στη λίστα, κάνε κλικ στο \'Το θέλω\' στην σελίδα του προϊόντος.</p></div></div>');		
	}
}

Havelist = {

	initialize : function() {
		
		if(!$('havelist'))
			return;
			
		this.loading 	= false;
		this.elements 	= $('havelist').getElements('.removeit');
		
		if(this.elements.length == 0)
			return;
			
		this.elements.addEvent('click', function(event) { 
		
			event.stopPropagation();
			event.preventDefault();
			
			Havelist.removeProduct(this); 
			
		});
	},
	
	removeProduct : function(element) {
		
		if(this.loading)
			return;
			
		this.loading = true;
		
		var pid = $(element).getProperty('data-pid');
		var parameters = {
			'action' 		: 'toggleHaveList',
			'status'		: 0,
			'productId'		: pid,
			'ak'			: window.User.ak,
			'isAjax'		: true
		};
		
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				Havelist.loading = false;
				
				if(parseInt(response.res.faultCode) > 0) {
				
					if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else
						alert('Σφάλμα: ' + response.res.faultString);

					return;
				}

				var item = $('pid-' + pid);

				item.setHTML('');
				item.setClass('empty');
				
				Havelist.td = $('havelist').getElements('td.product');
				$('tab-havelist').setHTML('<em>&nbsp;</em>Προϊόντα<span>που έχω (' + Havelist.td.length + ')</span>');
				
				if(Havelist.td.length == 0)
					$('havelist').getElement('.body').setHTML('<div class="pale"><div class="text"><p>Δεν έχεις προσθέσει ακόμη προϊόντα σε αυτή την λίστα</p><p class="sub">Για να προσθέσεις προϊόντα στη λίστα, κάνε κλικ στο \'Το έχω\' στην σελίδα του προϊόντος.</p></div></div>');
			},
		
			'parameters' : parameters
		
		}).send();
	}
}

PriceHistory = {
	
	initialize : function() {

		this.element = $('price-history');
		
		if(!this.element)
			return;
		
		if(window.ie8 || window.ie7 || window.ie6) { // deal with those in a later date
		
			$('price-history-header') && $('price-history-header').remove();
			this.element.remove();
		}

		this.overlay = new Overlay('', {

			'duration'	: 400,
			'className'	: 'overlay',
			'onOpen'	: function() 	{ this.element.addClass('overlay-normal'); },
			'beforeClose': function() 	{ this.element.removeClass('overlay-normal'); }
        });
		
		this.element.getElement('em').addEvent('click', this.renderHistory.bind(this));
	},
	
	renderHistory : function() {
	
		var html = [];

		html.push('<div class="overlay-inner">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Ιστορικό τιμών (20 ημέρες)<span class="close" onclick="PriceHistory.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body clr">');

		html.push('<iframe style=\"width:580px; height: 300px; background-color: #fff;\" id=\"overlay-history\" src=\"/tools/chart?id=' + this.element.getProperty('data-pid') + '\"></iframe>')

		html.push('</div>');	
		html.push('</div>');
		
		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();
	}
}

Carousel = {
	
	initialize : function() {
		
		if(!$('books-carousel'))
			return;
			
		this.gallery 	= $('books-carousel').getElement('.container');
		this.lis		= this.gallery.getElements('li');
		this.leftBttn	= $('book-car-left');
		this.rightBttn	= $('book-car-right');
		this.scrollFx	= new Fx.Scroll(this.gallery, {
			'duration' : 500
		});
		this.screenNum	= 0;

		this.leftBttn.addEvent('click', this.scrollRight.bind(this));
		this.rightBttn.addEvent('click', this.scrollLeft.bind(this));	
	},
	
	scrollRight : function() {
		
		if(this.screenNum == 0)
			return;
			
		this.screenNum--;

		this.scroll(this.screenNum * 3);
	},

	scrollLeft : function() {
		
		if(this.screenNum + 1 >= Math.ceil(this.lis.length / 3))
			return;
			
		this.screenNum++;
		
		this.scroll(this.screenNum * 3);
	},
	
	scroll : function(num) { 
		
		this.scrollFx.toElement((this.lis[num] ? this.lis[num] : this.lis[this.lis.length - 1])); 
	
		this.rightBttn.removeClass('inactive');
		this.leftBttn.removeClass('inactive');
		
		if(this.screenNum == Math.ceil(this.lis.length / 3) - 1)
			this.rightBttn.addClass('inactive');
		
		if(this.screenNum == 0)
			this.leftBttn.addClass('inactive');
	}
}

DealsSubscribe = {
	
	initialize : function() {
		
		this.elements = $('wrapper').getElements('.do-subscribe');
		
		if(this.elements.length == 0)
			return;

		this.elements.addEvent('click', function() { DealsSubscribe.toggleSubscribe(this); });
	},
	
	toggleSubscribe : function(element) {
		
		var isSub	= $(element).getProperty('data-sub');
		var cat 	= parseInt($(element).getProperty('data-cid'));
		
		if(cat == 0 || isSub == "" || isNaN(cat) || cat == null)
			return;

		isSub = parseInt(isSub);

		var parameters = {
			'action' 		: 'toggleCatSubscription',
			'ak'			: window.User.ak,
			'isAjax'		: true,
			'status'		: isSub,
			'cat'			: cat
		};
	
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				if(!response.res) {
					
					alert('Εμφανίστηκε κάποιο πρόβλημα, προσπάθησε ξανά.');
					return;
				}
				
				if(parseInt(response.res.faultCode) > 0) {
					
					if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else						
						alert('Σφάλμα: ' + response.res.faultString);
						
				} else {
				
					if($('page-deals')) {
						
						$(element).setProperty('data-sub', '');
						$(element).setHTML('Έχεις εγγραφεί στην κατηγορία<em class="link" onclick="window.location = \'/cat/' + cat + '\';">' + $(element).getElement('em').innerHTML + '</em>').addClass('success');
						
						var html = [];

						html.push('<h6>Η κατηγορία προστέθηκε<span class="close" onclick="$(\'catsub-popup\').remove();">×</span></h6>');
						html.push('<p>Μπορείς να διακόψεις την εγγραφή σου οποιαδήποτε στιγμή από <a href="/cat/' + cat + '">την σελίδα της κατηγορίας</a> ή <a href="/user/">την σελίδα των ρυθμίσεων</a></p>');

						$C('div', { 'id' : 'catsub-popup' }).setClass('contextual').setHTML(html.join('')).injectIn($('deals-subscribe'));					
						
					} else if($('page-user')) {
						
						$(element).getParent().remove();
						
						if($('sub-count')) {
							
							var left = parseInt($('sub-count').getElement('span').innerHTML) - 1;
							
							$('sub-count').setHTML('(<span>' + left + '</span>)');
							
							if(left == 0) {
							
								$C('p').setClass('pale').setHTML('Δεν έχεις εγγραφεί ακόμη σε κάποια κατηγορία.').injectAfter($('subbed-cats'));
								$('subbed-cats').remove();
							}
						}
							
					} else {	
		
						$(element).setProperty('data-sub', (isSub == 1 ? 0 : 1)).toggleClass('subscribed').setHTML((isSub == 1 ? "Εγγραφή" : "Διακοπή"));
					}
				}
			},
		
			'parameters' : parameters
		
		}).send();
	}
}

ClickBadge = {
	
	initialize : function() {
		
		this.elements = $('wrapper').getElements('.click-badge');
		
		if(this.elements.length == 0)
			return;
			
		this.overlay = new Overlay('', {

			'duration'	: 400,
			'className'	: 'overlay',
			'onOpen'	: function() 	{ this.element.addClass('overlay-normal'); },
			'beforeClose': function() 	{ this.element.removeClass('overlay-normal'); }
	   	});

		this.elements.addEvent('click', this.renderTable.bind(this));
	},
	
	renderTable : function(event) {

		event.stop();
		
		var html = [];

		html.push('<div class="overlay-inner">');

		html.push('<div class="overlay-header">');
		html.push('<h4>Προϋποθέσεις verified καταστημάτων<span class="close" onclick="ClickBadge.overlay.close();">x</span></h4>');
		html.push('</div>');
		html.push('<div class="overlay-body clr">');
		html.push('<table class="packages" cellpadding="0" cellspacing="0">');
		html.push('<thead>');
		html.push('<tr>');
		html.push('<th>Απαραίτητες Προϋποθέσεις</th>');
		html.push('<td><em class="verified">&nbsp;</em>Verified</td>');
		html.push('<td><em class="verified-plus">&nbsp;</em>Verified Plus</td>');
		html.push('</tr>');
		html.push('</thead>');
		html.push('<tbody>');
		html.push('<tr>');
		html.push('<th>Ελάχιστος  χρόνος συμμετοχής στην υπηρεσία</th>');
		html.push('<td>&gt; 3 μήνες</td>');
		html.push('<td>&gt; 6 μήνες</td>');
		html.push('</tr>');
		html.push('<tr> ');
		html.push('<th>Ταυτοποίηση στοιχείων επιχείρησης<sup>[1]</sup></th>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('</tr>');
		html.push('<tr>');
		html.push('<th>Διάρκεια λειτουργίας ηλεκτρονικού καταστήματος<sup>[1]</sup></th>');
		html.push('<td>&gt; 6 μήνες</td>');
		html.push('<td>&gt; 12 μήνες</td>');
		html.push('</tr>');
		html.push('<tr>');
		html.push('<th>Μέσος όρος βαθμολογίας χρηστών<sup>[2]</sup></th>');
		html.push('<td>3+</td>');
		html.push('<td>4+</td>');
		html.push('</tr>');
		html.push('<tr>');
		html.push('<th>Χρήση πρωτοκόλλου SSL</th>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('</tr>');
		html.push('<tr>');
		html.push('<th>Σύστημα παρακολούθησης παραγγελίας<sup>[3]</sup></th>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('</tr>');
		html.push('<tr>');
		html.push('<th>Προστασία προσωπικών δεδομένων</th>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('</tr>');
		html.push('<tr>');
		html.push('<th>Τήρηση πολιτικής επιστροφών</th>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('</tr>');
		html.push('<tr>');
		html.push('<th>Δυναμικά ανανεώσιμο XML</th>');
		html.push('<td><span class="no">Όχι</span></td>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('</tr>');
		html.push('<tr>');
		html.push('<th>Αναφορά διαθεσιμότητας προϊόντων</th>');
		html.push('<td><span class="no">Όχι</span></td>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('</tr>');
		html.push('<tr>');
		html.push('<th>Αρ. προμηθευτή εξ αποστάσεως</th>');
		html.push('<td><span class="no">Όχι</span></td>');
		html.push('<td><span class="yes">Ναι</span></td>');
		html.push('</tr>');
		html.push('</tbody>');
		html.push('</table>');
		html.push('<ol class="verified-tip">');
		html.push('<li>Η ταυτοποίηση των στοιχείων της επιχείρησης και ο έλεγχος της διάρκειας λειτουργίας από σύστασης (του ηλεκτρονικού καταστήματος) πραγματοποιείται από την Phaistos Networks Α.Ε.</li>');
		html.push('<li>Έως και την 31/12/2011, στην υπηρεσία θα συνυπολογίζεται και η βαθμολογία που είχαν συγκεντρώσει τα καταστήματα κατά τη διάρκεια της συμμετοχής τους στην προηγούμενη έκδοση της υπηρεσίας.</li>');
		html.push('<li>Δυνατότητα παρακολούθησης της παραγγελίας σε όλα τα στάδια έως και την παράδοσή της.</li>');
		html.push('</div>');	
		html.push('</div>');

		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();
	}
}

ToggleFollow = {
	
	initialize : function() {
		
		if(!$('content'))
			return;
			
		this.elements = $('content').getElements('.follow');
		
		if(this.elements.length == 0)
			return;
		
		this.elements.addEvent('click', function() { ToggleFollow.send(this); });
	},
	
	send : function(element) {
		
		if(this.loading)
			return;
		
		this.loading 	= true;
		
		var username	= (element.getProperty('data-uname') !== null ? element.getProperty('data-uname') : "");
		var willFollow	= parseInt(element.getProperty('data-follow'));
		var uid			= parseInt(element.getProperty('data-uid'));
		var parameters 	= {
			'action' 		: 'toggleFollow',
			'ak'			: window.User.ak,
			'isAjax'		: true,
			'willFollow'	: willFollow,
			'uid'			: uid,
			'username'		: username
		};
		
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				ToggleFollow.loading = false;
				
				if(!response.res) {
					
					alert('Εμφανίστηκε κάποιο πρόβλημα, προσπάθησε ξανά.');
					return;
				}
				
				if(parseInt(response.res.faultCode) > 0) {
					
					if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else						
						alert('Σφάλμα: ' + response.res.faultString);
						
				} else {
				
					if(willFollow == 1)
						element.addClass('following').setProperty('data-follow', '0').setHTML((username == '' ? 'Διακοπή' : 'Ακολουθείς τον χρήστη ' + username));
					else
						element.removeClass('following').setProperty('data-follow', '1').setHTML((username == '' ? 'Ακολούθησέ τον' : 'Ακολούθησε τον χρήστη ' + username));
				}
			},
		
			'parameters' : parameters
		
		}).send();
	}
}

FollowersTicker = {
	
	initialize : function() {
		
		if(!$('wishlisted-products'))
			return;
	
		this.interval 	= 5000;
		this.animating 	= false;		
		this.active 	= 0;
		this.elements 	= $('wishlisted-products').getElements('li');
		
		this.timerId = this.getNext.delay(this.interval, this);
	},
	
	selectStory : function(element, newIndex) {

		if(this.animating)
			return;

		if(!element)
			return;

		var activeElement 	= this.elements[this.active];

		// fade out the active
		new Fx.Style(activeElement, 'opacity', { 

			'duration' : 300,
			'onComplete' : function() {

				// fade in the new		
				new Fx.Style(element, 'opacity', { 

					'duration' 		: 300,
					'onComplete'	: function() { FollowersTicker.animating = false; }

				}).start(0, 1);
			} 

		}).start(1, 0);
		
		// update the active index
		this.active 	= newIndex;
		this.timerId 	= this.getNext.delay(this.interval, this);
	},

	getNext : function() {

		if(this.animating)
			return;

		var newIndex = 0;

		if(this.active == this.elements.length - 1)
			newIndex = 0;
		else
			newIndex = this.active + 1;

		var element = this.elements[newIndex];

		this.selectStory(element, newIndex);
	}
}

BigImage = {
	
	initialize : function() {
		
		if(!$('big-image'))
			return;
			
		if(!$('feat-tabs'))
			return;
	
		this.active 	= 0;
		this.overlayAct = 0;
		this.timerId 	= 0;
		this.interval 	= 7000;
		this.animating 	= false;
		this.opened 	= false;		
		this.images		= $('big-image').getElements('li');
		this.dots 		= $('feat-tabs').getElements('td');
		
		var firstTab = this.dots[0];
		
		this.startX = ((parseInt(firstTab.getStyle('width')) + 25) / 2);

		$('knob').setStyles({
			'-webkit-transform' : 'translate3d(' + this.startX + 'px, 0, 0)',
			'-moz-transform' 	: 'translate(' + this.startX + 'px, 0)',
			'msTransform' 		: 'translate(' + this.startX + 'px, 0)'
		}).show();
		
		// New implementation
		this.featImages = [];

		this.images.each(function(value, index) {
			
			BigImage.featImages.push({
				'img' 	: this.getElement('img').getProperty('src'),
				'url' 	: this.getElement('a').getProperty('href'),
				'tab' 	: BigImage.dots[index],
				'descr' : this.getElement('a').getProperty('title')
			});
		});
		
		$C('div', { 'id' : 'feat-image-container' }).setStyles({
			'overflow' 	: 'hidden',
			'width' 	: '688px',
			'height'	: '445px' /*467*/
		}).injectIn($('big-image')).hide();
		
		this.slideshow = new Slideshow.Fade(this.featImages, $('feat-image-container'), {

			'interval'		: 7000,
			'preloadAsync' 	: false,
			'autoPlay' 		: true,
			'clicky'		: true,
			'dumpLoader' 	: function() { return ''; },
			'onLoadComplete': function() {
				
				$('big-image').getElement('ul').remove();
				$('feat-image-container').show();
			},
			'onChange' 		: function(index, slide) {
				
				// remove the old active
				BigImage.dots.each(function() { this.removeClass('active'); });

				// set the dot as active
				slide.tab.addClass('active');

				// refresh knob
				var newX = ((index - 1) * (parseInt(slide.tab.getStyle('width')) + 25) + BigImage.startX) + 'px';

				$('knob').setStyles({
					'-webkit-transform' : 'translate3d(' + newX + ', 0, 0)',
					'-moz-transform' 	: 'translate(' + newX + ', 0)',
					'msTransform' 		: 'translate(' + newX + ', 0)'
				});
			}
		});
		
		this.dots.addEvent('mouseover', function() {
			
			var index = parseInt(this.getProperty('data-dot')) + 1;
			
			BigImage.slideshow.gotoSlide(index);
		});
		
		return;
		
		this.dots 	= $('feat-tabs').getElements('td');
		this.dots.addEvent('mouseover', function() {

			clearTimeout(BigImage.timerId);
			
			BigImage.selectImage(this, true); 
		});
		
		if(this.dots.length == 0)
			return;
		
		var firstTab = this.dots[0];
		
		this.startX = ((parseInt(firstTab.getStyle('width')) + 25) / 2);

		$('knob').setStyles({
			'-webkit-transform' : 'translate3d(' + this.startX + 'px, 0, 0)',
			'-moz-transform' 	: 'translate(' + this.startX + 'px, 0)',
			'msTransform' 		: 'translate(' + this.startX + 'px, 0)'
		}).show();
		
		this.timerId = this.getNext.delay(this.interval, this);
	},
	
	selectImage : function(dot, force) {
	
		if(this.animating)
			this.fx && this.fx.stop();
		
		if(!dot)
			return;
			
		if(dot.hasClass('active'))
			return;
			
		var index 		= parseInt(dot.getProperty('data-dot'));	
		var activeImg 	= this.images[this.active];
		var newImg		= this.images[index];

		this.fx = new Fx.Style(activeImg, 'opacity', { 

			'duration' : 200,
			'onComplete' : function() {

				new Fx.Style(newImg, 'opacity', { 
			
					'duration' 		: 200,
					'onComplete'	: function() { BigImage.animating = false; }
			
				}).start(0, 1);
			} 

		}).start(1, 0);

		// remove the old active
		this.dots.each(function() { this.removeClass('active'); });
		
		// set the dot as active
		dot.addClass('active');
	
		// refresh knob
		var newX = (index * (parseInt(dot.getStyle('width')) + 25) + this.startX) + 'px';

		$('knob').setStyles({
			'-webkit-transform' : 'translate3d(' + newX + ', 0, 0)',
			'-moz-transform' 	: 'translate(' + newX + ', 0)',
			'msTransform' 		: 'translate(' + newX + ', 0)'
		});
		
		// update the active index
		this.active 		= index;
		
		if(!force)
			this.timerId = this.getNext.delay(this.interval, this);
	},
	
	getNext : function() {
		
		if(this.animating || !this.dots)
			return;
			
		var newIndex = 0;
		
		if(this.active == this.dots.length - 1)
			newIndex = 0;
		else
			newIndex = this.active + 1;
			
		var dot = this.dots[newIndex];
		
		this.selectImage(dot);
	}
}

Nearby = {
	
	initialize : function() {
		
		if(!$('nearby'))
			return;
	
		this.isLoading 			= false;
		this.perPage			= 6;
		this.radius				= 10;
		this.loaded 			= false;	
		this.mapContainer 		= $('nearby-map');
		this.header				= $('nearby-header');
		this.tab 				= $('tab-nearby');
		this.loadingHTML		= this.mapContainer.innerHTML;
		this.mids				= JSON.parse(this.mapContainer.getProperty('data-mids').replace(/\'/gi, '"'));
		this.merchantIds		= [];
		this.merchantsHash		= {};
		
		this.mids.each(function() {

			Nearby.merchantIds.push(this.id);
			Nearby.merchantsHash[this.id] = {
				'price' : this.price,
				'path'	: this.link,
				'av'	: this.av
			};
		});
		
		this.mylocation			= $('my-location').getElement('em');
		this.locationLegend		= $('my-location').getElement('span');
		
		if(this.mapContainer.getProperty('data-lat') != "" && this.mapContainer.getProperty('data-lon') != "") {
			
			userLat = parseFloat(this.mapContainer.getProperty('data-lat'));
			userLon = parseFloat(this.mapContainer.getProperty('data-lon'));
		}
		
		this.mylocation.addEvent('click', function(event) {
		
			event.stop();
			
			if(!Nearby.map)
				return;
				
			var myLatLng = new google.maps.LatLng(userLat, userLon);
			
			Nearby.map.panTo(myLatLng);
		});
	},

	loading 	: function() { 
		
		this.isLoading = true;
		this.mapContainer.setHTML(this.loadingHTML); 
	},
	
	getStores	: function() {
		
		if(this.isLoading)
			return;
			
		this.loading();
		
		var parameters = {
			'action' 		: 'getNearbyStores',
			'mids'			: this.merchantIds,
			'ak'			: window.User.ak,
			'isAjax'		: true
		};
		
		if (typeof window.User.ak == 'undefined' && typeof(localStorage) != 'undefined' && localStorage['userlatlon'] != '' && typeof localStorage['userlatlon'] != 'undefined') {
		
			var userTempLoc = JSON.parse(localStorage['userlatlon']);

			if(userTempLoc != null && userTempLoc.lat != null && userTempLoc.lon != null) {

				parameters.lat = userTempLoc.lat;
				parameters.lon = userTempLoc.lon;

				MyLocation.updateNonLoggedInLocation(userTempLoc, false);
			}
		}
		
		if(typeof window.User.ak == 'undefined' && userLat && userLon) {
			
			parameters.lat = userLat;
			parameters.lon = userLon;
		}

		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				Nearby.isLoading = false;
				
				var response = this.responseJSON;

				if(response === null)
					return;
					
				if(parseInt(response.res.faultCode) > 0) {
				
					alert('Σφάλμα: ' + response.res.faultString);
					return;
				}
										
				if(response.res.no_latlng === true) {
					
					Nearby.mapContainer.setHTML('<div class="nolatlng"><a href="javascript:void(0);" onclick="MyLocation.render();">Κάνε κλικ εδώ για να ορίσεις τοποθεσία</a></div>');
					return;
				}
				
				if(isNaN(userLat) || isNaN(userLon)) {
				
					userLat = response.res.center.lat;
					userLon = response.res.center.lon;
				}
				
				Nearby.stores = response.res;
				Nearby.radius = Nearby.stores.radius;
				
				Nearby.header.getParent().show();
				
				Nearby.tab.setHTML('<em>&nbsp;</em>Κοντά σου' + (Nearby.stores.points.length > 0 ? ' (' + Nearby.stores.points.length + ')' : ''));

				if(Nearby.stores.points.length == 0)
					Nearby.header.setHTML('Κοντινά καταστήματα σε ακτίνα ' + Nearby.radius + ' χιλιομέτρων');
				else if(Nearby.stores.points.length == 1)
					Nearby.header.setHTML('1 κοντινό κατάστημα σε ακτίνα ' + Nearby.radius + ' χιλιομέτρων');
				else
					Nearby.header.setHTML(Nearby.stores.points.length + ' κοντινά καταστήματα σε ακτίνα ' + Nearby.radius + ' χιλιομέτρων');
					
				Nearby.renderMap(0);
			},
		
			'parameters' : parameters
		
		}).send();	
	},
	
	openInfoBox	: function(index) {

		if(this.activeBox == index)
			return;
		
		if(typeof this.activeBox != 'undefined') {
			
			this.infoboxes[this.activeBox].close();
			$('map-stores').getElement('li[data-index="' + this.activeBox + '"]').removeClass('active');
		}
		
		this.infoboxes[index].open(this.map, this.markers[index]);
			
		$('map-stores').getElement('li[data-index="' + index + '"]').addClass('active');
		
		this.activeBox = index;
	},
	
	route : function(fLat, fLon, tLat, tLon) {
		
		if(typeof this.activeBox != 'undefined')
			this.infoboxes[this.activeBox].close();
			
		var fromLatLng 	= new google.maps.LatLng(fLat, fLon);
		var toLatLng	= new google.maps.LatLng(tLat, tLon);
		
	    var request = {
			'origin'		: fromLatLng, 
			'destination'	: toLatLng,
			'travelMode'	: google.maps.DirectionsTravelMode.DRIVING
	    };
	
	    this.dirService.route(request, function(response, status) {
		
			if (status == google.maps.DirectionsStatus.OK)
	        	Nearby.directions.setDirections(response);
	    });
	},
	
	renderMap 	: function(pg) {
		
		if(pg == 0 && this.stores.points.length == 0) {
		
			this.mapContainer.setClass('pale').setHTML('Δεν βρέθηκαν καταστήματα κοντά σου που να διαθέτουν το προϊόν! <a href="javascript:void(0);" onclick="MyLocation.render();">Άλλαξε διεύθυνση</a> και προσπάθησε ξανά. :(');
			return;
		}
		
		this.mapContainer.removeClass('pale');

		var center = new google.maps.LatLng(this.stores.center.lat, this.stores.center.lon);
		var html = "";
		
		html += "<div id=\"map-container\" class=\"clr\">";
		html += "<div id=\"map-box\">";
		html += "</div>";
		html += "<div id=\"map-stores\">";
		html += "</div>";
		html += "</div>";
		
		this.mapContainer.setHTML(html);
		
		this.pg 		= pg;
		this.activeBox	= undefined;
		this.markers 	= [];
		this.infoboxes	= [];
	  	this.dirService = new google.maps.DirectionsService();
		this.directions = new google.maps.DirectionsRenderer({
			'draggable' 			: true,
			'suppressInfoWindows'	: true
		});
		this.map 		= new google.maps.Map($('map-box'), {
			'zoom' 				: 13,
			'mapTypeId'			: google.maps.MapTypeId.ROADMAP,
			'streetViewControl'	: false,
			'mapTypeControl'	: false,
			'panControl'		: false,
		    'zoomControlOptions': {
		    	'style': google.maps.ZoomControlStyle.SMALL
		    }
		});
		
		this.directions.setMap(this.map);
		
		var mapBounds 	= new google.maps.LatLngBounds();
		var myLatLng 	= new google.maps.LatLng(userLat, userLon);
		var marker 		= new google.maps.Marker({
	      	'position'	: myLatLng,
	     	'map'		: Nearby.map,
	     	'draggable'	: false,
	     	'animation'	: google.maps.Animation.DROP,
			'icon'		: 'http://www.google.com/intl/en_us/mapfiles/ms/micons/blue-dot.png'
	    });
		
		mapBounds.extend(myLatLng);
		
		var list		= "<ul>";
		var totalViewed = 0;
		
		for(var i = (pg * this.perPage); i < (pg * this.perPage) + this.perPage; i++) {
			
			var store 		= this.stores.points[i];
			
			if(!store)
				continue;
				
			var position 	= new google.maps.LatLng(store.lat, store.lon);
			var merchant	= this.stores.merchants[store.mid];
			var mHash		= Nearby.merchantsHash[merchant.id];
			
			mapBounds.extend(position);
			
			var marker = new google.maps.Marker({
		      	'position'	: position,
		     	'map'		: Nearby.map,
		     	'draggable'	: false,
		     	'animation'	: google.maps.Animation.DROP,
				'index'		: i
		    });
		
			var directionsFunc = "Nearby.route(" + userLat + "," + userLon + "," + store.lat + "," + store.lon + ");";
		
			var infobox	= new google.maps.InfoWindow({
				'content'	: 	'<div class="infobox">' +
								'<img src="' + merchant.logo + '" width="45" height="15"/>' +
								'<h6><a href="/m/' + merchant.id + '" target="_blank">' + merchant.title + ' &raquo;</a></h6>' +
								'<p class="price"><a rel=\"nofollow\" target="_blank" href="/item/' + mHash.path + '">' + mHash.price + '</a></p>' +
								'<p class="address">' + store.address + '</p>' +
								(store.phone && store.phone != '' ? '<p>Τηλ. ' + store.phone + '</p>' : '') +
								'<p><a href="javascript:void(0);" onclick="' + directionsFunc + '">Διαδρομή</a></p>' +
								'</div>'
			});

			Nearby.markers[i] 	= marker;
			Nearby.infoboxes[i] = infobox;
		
			list += "<li class=\"store" + (totalViewed == 0 ? " first" : "") + (this.stores.points.length <= this.perPage ? " bottom" : "") + "\" data-index=\"" + i + "\" onmouseover=\"Nearby.openInfoBox(" + i + ");\" onclick=\"" + directionsFunc + "\">";
			list += "<h6>";
			list += "<a class=\"more\" target=\"_blank\" href=\"/m/" + merchant.id + "\">";
			list += merchant.title;
			list += " &raquo;</a>";
			list += "<span><a rel=\"nofollow\" target=\"_blank\" href=\"/item/" + mHash.path + "\">" + mHash.price + "</a></span>";
			list += "</h6>";
			
			list += "<div class=\"info" + (merchant.verified > 0 ? " badge " + (merchant.verified == 1 ? "verified" : "verified-plus") : "") + "\">";
			
			list += "<p class=\"address\"><em>~ " + (store.distance >= 1 ? parseInt(store.distance) : store.distance.toFixed(2)) + " χλμ.</em> " + store.address + "</p>";
			
			if(store.phone && store.phone != '')
				list += "<p class=\"tel\"><strong>Τηλ.</strong> " + store.phone + "</p>";
			
			list += "</div>";
				
			list += "</li>";
			
			google.maps.event.addListener(marker, 'click', function() { Nearby.openInfoBox(this.index); });
			
			totalViewed++;
		}

		list += "</ul>";
		
		if(this.stores.points.length > this.perPage) {
			
			list += "<p class=\"pages\">";
			
			if((pg * this.perPage + 1) > 1) {
				
				list += "<a class=\"left-link\" href=\"javascript:void(0);\" onclick=\"Nearby.renderMap(" + (Nearby.pg - 1) + ")\">";
				list += "&laquo; Προηγούμενα";
				list += "</a>";
			}
			
			list += (pg * this.perPage + 1);
			list += " - ";
			list += ((pg * this.perPage) + totalViewed);
			list += " από ";
			list += this.stores.points.length;
			
			if((pg * this.perPage) + this.perPage < this.stores.points.length) {
				
				list += "<a class=\"right-link\" href=\"javascript:void(0);\" onclick=\"Nearby.renderMap(" + ((Nearby.pg + 1)) + ")\">";
				list += "Επόμενα &raquo;";
				list += "</a>";
			}
			
			list += "</p>";
		}
		
		this.map.fitBounds(mapBounds);
		
		//	if(totalViewed == 1)
		//		this.map.setZoom(13);
			
		$('map-stores').setHTML(list);
		
		this.loaded = true;
	}
}

StreamMore = {
	
	initialize : function() {
		
		if(!$('stream-more'))
			return;
	
		this.loading= false;	
		this.stream = $('general').getElement('.stream');
	},
	
	loadMore : function(button) {
		
		var id 	= parseInt($(button).getProperty('data-lastid'));
		var uid	= parseInt($(button).getProperty('data-uid'));
		
		this.uid = uid;
		this.getStream(id, button);		
	},
	
	getStream : function(id, button) {
		
		if(this.loading)
			return;
			
		var parameters = {
			'action' 	: 'getStream',
			'userId'	: this.uid,
			'lastId'	: id,
			'isAjax'	: true
		};	
		
		new Ajax('post', {

			'encoding' : 'utf-8',

			onSuccess : function()	{

				StreamMore.isLoading = false;

				var response = this.responseJSON;

				if(response === null)
					return;

				if(parseInt(response.res.faultCode) > 0) {

					alert('Σφάλμα: ' + response.res.faultString);
					return;
				}
				
				if(response.res.stream && response.res.stream != "")
					response.res.stream.injectIn(StreamMore.stream);
				
				$(button).getParent().remove();
			},

			'parameters' : parameters

		}).send();
	}
}

Invite = {
	
	initialize : function() {
		
		if(!$('contacts'))
			return;
			
		this.elements = $('contacts').getElements('.mail-button');
		
		if(this.elements.length == 0)
			return;
			
		this.overlay = new Overlay('', {

			'duration'	: 400,
			'className'	: 'overlay',
			'onOpen'	: function() 	{ this.element.addClass('overlay-normal'); },
			'beforeClose': function() 	{ this.element.removeClass('overlay-normal'); }
	   	});
	
		this.elements.addEvent('click', function() { Invite.showModal(this); });
	},
	
	showModal : function(element) {
		
		this.element = element;
		
		this.cid = parseInt($(element).getProperty('data-cid'));

		var name = $(element).getProperty('data-name');		
		var html = [];

		html.push('<div class="overlay-inner">');

		html.push('<div class="overlay-header">');
		html.push('<h4>Κάλεσε τον ' + (name && name !== '' ? 'χρήστη ' + name : 'φίλο σου') + ' στο BestPrice<span class="close" onclick="Invite.overlay.close();">x</span></h4>');
		html.push('</div>');
		html.push('<div class="overlay-body clr" id="invite-overlay">');
		
		html.push('<h5 style="font-size: 14px; margin-bottom: 10px;">Πρόσθεσε ένα προσωπικό μήνυμα (προαιρετικό)</h5>');
		
		html.push('<textarea name="message" id="invite-msg" class="field" style="width:98%;height:8em"></textarea>');
		
		html.push('<p class="choices"><a class="button" onclick="Invite.submit();">Αποστολή πρόσκλησης</a> ή <a href="javascript:void(0);" onclick="Invite.overlay.close();">κλείσιμο</a></p>');

		html.push('</div>');	
		html.push('</div>');

		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();
	},
	
	submit : function() {
		
		var parameters = {
			'action' 		: 'sendInvite',
			'cid'			: this.cid,
			'msg'			: $('invite-msg').getValue(),
			'ak'			: window.User.ak,
			'isAjax'		: true
		};
		
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				if(parseInt(response.res.faultCode) > 0) {
				
					if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else						
						alert('Σφάλμα: ' + response.res.faultString);
					
					return;
				} 
				
				$('invite-overlay').setHTML('<p class="thanks-feedback">Η πρόσκλησή σου στάλθηκε!</p><p style="text-align: center;" class="choices"><a href="javascript:void(0);" class="button" onclick="Invite.overlay.close();">Κλείσιμο</a></p>');
				
				Invite.element.getParent().setHTML('<span class="invite">Έχει σταλεί πρόσκληση</span>');
			},
		
			'parameters' : parameters
		
		}).send();
	}
}

SaveSettings = {

	initialize : function() {
		
		if(!$('account-settings'))
			return;

		this.loading 	= false;			
		this.elements 	= $('account-settings').getElements('input');
		
		if(this.elements.length == 0)
			return;
			
		this.elements.addEvent('change', function() { SaveSettings.send(this); });
	},
	
	send : function(element) {
		
		if(this.loading)
			return;

		this.loading = true;
	
		var type = $(element).getProperty('data-type');
		var value= ($(element).checked ? 1 : 0);
		
		var privacy 		= (parseInt($(element).getProperty('data-privacy')) == 1);
		var notification	= !privacy;
		
		var parameters = {
			'action' 		: 'saveSettings',
			'ak'			: window.User.ak,
			'isAjax'		: true,
			'type'			: type,
			'value'			: value,
			'privacy'		: (privacy == true ? 1 : 0),
			'notification'	: (notification == true ? 1 : 0)
		};
		
		if(type == 'stream' && value == 0) {
			
			var answer = confirm("Απενεργοποιώντας την εμφάνιση της δραστηριότητας, σβήνεται αυτόματα όλο το ιστορικό των ενεργειών σου. Είσαι σίγουρος/η;");

			if(!answer) {
				
				$(element).checked = !value;
				this.loading = false;
				return;
			}
		}
		
		$(element).hide();

		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{

				var response = this.responseJSON;

				SaveSettings.loading = false;
				
				$(element).show();
				
				if(parseInt(response.res.faultCode) > 0) {
				
					if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else						
						alert('Σφάλμα: ' + response.res.faultString);
				
					$(element).checked = !value;
					
					return;
				}
			},
		
			'parameters' : parameters
		
		}).send();
	}
}

BadgeGenerator = {
	
	initialize : function() {
		
		if(!$('badge-generator'))
			return;
			
		this.elements = $('badge-generator').getElements('input');
		
		if(this.elements.length == 0)
			return;
			
		this.textarea = $('badge-generator').getElement('textarea');
		
		this.elements.addEvent('click', this.rebuild.bind(this));
		
		this.rebuild();
	},
	
	rebuild : function() {
		
		var size 	= 'normal';
		var link 	= 'store';
		var secure	= 'no';
		
		if($('size-small').checked)
			size = 'small';
		
		if($('secure-yes').checked)
			secure = 'yes';
		
		if($('link-products').checked)
			link = 'products';
		else if($('link-none').checked)
			link = 'none';
		
		var host 	= '';
		
		if(secure == 'yes')
			host = 'https://secure';
		else if(window.location.host.indexOf('dev') !== -1)
			host = 'http://v2.dev';
		else
			host = 'http://www';
		
		var value = '<script' + (size == 'small' ? ' data-size="small"' : '') + (secure == 'yes' ? ' data-secure="yes"' : '') + (link != 'store' ? ' data-link="' + link + '"' : '') + ' src="' + host + '.bestprice.gr/tools/badge.js" async="true"></script>';
		
		this.textarea.setValue(value);
		
		var urlArgs = [];	
		urlArgs.push('secure=' + secure);
		urlArgs.push('size=' + size);
		urlArgs.push('link=' + link);

		$('badge-preview').setHTML('');
	
		$C('iframe', {

			'allowTransparency' : true,
			'frameBorder'		: 0,
			'tabIndex'			: 0,
			'scrolling'			: 'no',
			'src'				: host + '.bestprice.gr/tools/badge.php' + (urlArgs.length > 0 ? '?' + urlArgs.join('&') : '')

		}).setStyles({
			
			'border'			: 'none',
			'width'				: (size == 'small' ? '116px' : '154px'),
			'height'			: (size == 'small' ? '84px' : '124px'),
			'overflow'			: 'hidden',
			'vertical-align'	: 'middle'
			
		}).injectIn($('badge-preview'));
	}
}

ItemFilter = {
	
	initialize : function() {

		if(!$('item-filter'))
			return;

		this.cartProducts 		= $('prices').getElements('.physical-products tr[data-hascart="true"]');
		this.buildCartToggler();
					
		this.labels = $('item-filter').getElements('label');
		
		this.labels.addEvent('click', function() {
		
			ItemFilter.labels.removeClass('checked');
			$(this).addClass('checked');
			
			var name = $(this).getProperty('for');
			
			ItemFilter.selectFilter(name);
		});

		this.pricesTable		= $('prices').getElement('table');
		this.verifiedProducts 	= $('prices').getElements('.physical-products tr[data-verified="1"]');
		this.allProducts 		= $('prices').getElements('.physical-products tr');
		this.freeShip			= $('prices').getElements('.physical-products tr[data-freeship="1"]');
		
		this.filters = $('item-filter').getElements('span');
		
		this.filters.addEvent('click', function() {
		
			var name = $(this).id;
			
			ItemFilter.selectFilter(name);
		});
	},
	
	buildCartToggler : function() {
		
		if(this.cartProducts.length == 0)
			return;
		
		var html = '';
			
		html += '<span class="filter" id="filter-cart"></span>';
		html += '<label for="filter-cart" class="cartsort-label">Αγορά από BestPrice (' + this.cartProducts.length + ')</label>';

		html.injectIn($('item-filter'));
	},

	selectFilter : function(name) {
		
		var changed = false;
		
		this.filters.each(function() {
			
			if(this.id == name && !$(name).hasClass('checked')) {
				
				changed = true;
				$(this.id).addClass('checked');
				
			} else if(this.id != name)
				$(this.id).removeClass('checked');
		});
		
		if(changed) {
			
			ProductsExpander.collapseAll();
			
			if(name == 'filter-cart') {

				this.allProducts.hide();
				this.cartProducts.show();

			} else if(name == 'filter-freeship') {
				
				this.allProducts.hide();
				this.freeShip.show();

			} else if(name == 'filter-verifiedm') {
				
				this.allProducts.hide();
				this.verifiedProducts.show();
				
			} else {
				
				this.allProducts.each(function() {
					
					if(!this.hasClass('secondary'))
						this.show();
				});
			}

			this.pricesTable.setClass(name);
		}
	}
}

ItemSort = {

	rows 	: [],
	table 	: null,
	trigger : null,
	sorting : false,

	toRestore : [],

	initialize : function () {

		if (!(this.table = $('#prices table')))
			return this;

		// Alter price cell
		$('#prices table thead .price').innerHTML += ' (<a href="javascript:void(0)" class="clicky_log" style="font-weight: normal;">Εμφάνιση βάσει τιμής</a>)';

		// Attach trigger
		this.trigger = $('#prices table thead .price a').
		addEvent('click', this.toggle.bind(this));

		return this;
	},

	toggle : function () {
		return this[!this.sorting ? 'sort' : 'revert']();
	},

	sort : function () {
		this.sorting = true;
		this.rows = $$('#prices tbody.physical-products tr');

		// Assign a revert-index
		this.rows.each(function (row, index) {
			row.setProperty('data-revert-index', index);
			row.__parent = row.getParent();
		});

		// Gather secondary rows
		this.rows.each(function (row, index) {
			var secondaries = [], next = row;

			while ((next = next.getNext()) && next.className === 'secondary') {
				secondaries.push(next);
			}

			if (secondaries.length) {
				row.secondaries = secondaries;
			}
		});

		// Create a new tbody to hold the rows
		var tBody = $C('tbody').setClass('physical-products');

		// Sort + put back
		this.rows.sort(this.sortFn).each(function (item, index) {
			if (item.__skip) {
				return;
			}

			tBody.adopt(item);

			if (item.secondaries) {
				item.secondaries.each(function (row, index) {
					row.__skip = true;
					tBody.adopt(row);
				});
			}			
		});

		// Remove t[body|head]s from the table
		this.table.getElements('tbody.physical-products').each(function (item, index) {
			if (item.getPrevious().nodeName === 'THEAD') {
				item.__thead = item.getPrevious();
				this.toRestore.push(item.__thead);
				item.__thead.remove();	
			}

			this.toRestore.push(item);
			item.remove();
		}, this);	

		// Adopt the new tbody
		this.table.adopt(tBody);
		this.tBody = tBody;

		this.trigger.setHTML('Κανονική εμφάνιση');

		return this;
	},

	sortFn : function (a, b) {
		var aPrice = parseFloat(a.getElement('.price-tag').getText().replace(/<sup>(.*?)\$<\/sup>/gi, '.$1'));
		var bPrice = parseFloat(b.getElement('.price-tag').getText().replace(/<sup>(.*?)\$<\/sup>/gi, '.$1'));

		return aPrice - bPrice;		
	},

	revert : function () {
		this.sorting = false;

		this.tBody.remove();

		//console.log(this.toRestore);
		this.toRestore.each(function (element, index) {
			if (element.__thead) {
				this.table.adopt(element.__thead);
			}
			this.table.adopt(element);
		}, this);

		this.rows.each(function (item, index) {
			if (item.__skip) {
				return false;
			}

			item.__parent.adopt(item);

			if (item.secondaries) {
				item.secondaries.each(function (row, index) {
					row.__skip = true;
					item.__parent.adopt(row);
				});
			}	
		});

		this.trigger.setHTML('Εμφάνιση βάση τιμής');

		return this;
	}
}


UserMenu = {
	
	initialize : function() {
		
		if(!$('umenu-toggler'))
			return;
	
		this.interval = 15000;
				
		document.addEvent('click', function(event) {

			if(	UserMenu.popup && 
				!UserMenu.toggler.contains(event.target) &&
				!UserMenu.popup.contains(event.target) && 
				event.target.id != 'user-menu-popup' && 
				event.target.id != 'umenu-toggler'
			) {
				UserMenu.hide();
			}
		});

		document.addEvent('keyup', function(event) { 

			if(event.code == 27) {

				if(!UserMenu.popup.isHidden())
					UserMenu.hide();
			}
		});
		
		this.popup = $('user-menu-popup');
		this.toggler = $('umenu-toggler');
		this.toggler.addEvent('click', this.toggle.bind(this));
		
		this.refresh.delay(this.interval, this);
	},
	
	toggle : function() {
		
		if(!this.toggler.hasClass('opened')) {
		
			$('contextual-welcome') && $('contextual-welcome').remove();
				
			CategoriesHeader.hide();
			this.setAsRead();
		}
		
		this.popup && this.popup.toggle();
		this.toggler && this.toggler.toggleClass('opened');
	},
	
	hide : function() {
		
		this.popup && this.popup.hide();
		this.toggler && this.toggler.removeClass('opened');
	},
	
	setAsRead : function() {
		
		var parameters = {
			'action' 		: 'setNotificationsRead',
			'ak'			: window.User.ak,
			'isAjax'		: true
		};
	
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				if(!response.res || parseInt(response.res.faultCode) > 0)
					return;
			},
		
			'parameters' : parameters
		
		}).send();
	},
	
	refresh : function() {
		
		var parameters = {
			'action' 		: 'getNotifications',
			'ak'			: window.User.ak,
			'isAjax'		: true
		};
	
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				// ADDED: !response
				if(!response || !response.res || parseInt(response.res.faultCode) > 0)
					return;
					
				if(parseInt(response.res.unread) > 0)
					$('notification-counter').setHTML(response.res.unread).show();
				else
					$('notification-counter').setHTML('').hide();
					
				$('notification-container').setHTML(response.res.notifications);
				
				UserMenu.refresh.delay(UserMenu.interval, UserMenu);
			},
		
			'parameters' : parameters
		
		}).send();		
	}
}

AutoPublish = {

	initialize : function() {
		
		if(!$('auto-facebook') && !$('auto-twitter'))
			return;

		this.loading = false;
					
		$('auto-facebook') && $('auto-facebook').addEvent('click', function() { AutoPublish.toggle($(this)); });	
		$('auto-twitter') && $('auto-twitter').addEvent('click', function() { AutoPublish.toggle($(this)); });
	},
	
	toggle : function(element) {
	
		if(this.loading)
			return;

		this.loading = true;
		
		var type 		= $(element).getProperty('data-type');
		var value		= ($(element).checked ? 1 : 0);
		var li 			= $('general').getElement('.linked-services li[data-service="' + type + '"]')
		var parameters 	= {
			'action' 		: 'toggleAutoPublish',
			'ak'			: window.User.ak,
			'isAjax'		: true,
			'type'			: type,
			'value'			: value
		};

		if(type == 'facebook' && value == 1)
			$C('div', { 'id' : 'loading-service' }).setHTML('Παρακαλώ περίμενε&hellip;<br/><progress></progress>').injectIn(li);

		$(element).hide();

		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{

				var response = this.responseJSON;

				AutoPublish.loading = false;
				
				$(element).show();
				
				if(parseInt(response.res.faultCode) > 0) {
				
					$(element).checked = !value;
					$('loading-service') && $('loading-service').remove();

					if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else						
						alert('Σφάλμα: ' + response.res.faultString);
							
					return;
				}
				
				if(response.res.requestMorePermissions)	{
					
					$(element).checked = !value;	
					window.location.href = '/?action=buildRequestMoreFBPermissionsURL&ak=' + window.User.ak;
					return;
				}
				
				$('loading-service') && $('loading-service').remove();
			},
		
			'parameters' : parameters
		
		}).send();
	}
}

ReviewReply = {
	
	initialize : function() {
		
		if(!$('page-m') || !$('reviews'))
			return;

		this.loading 	= false;
		this.fx 		= new Fx.Scroll();
			
		this.reviews = $('reviews').getElements('a[data-action="merchant-reply"]');

		if(this.reviews.length > 0) {
			
			this.reviews.addEvent('click', function() {
			
				var parentId = parseInt($(this).getProperty('data-parentid'));
			
				ReviewReply.show(parentId, $(this).getParent().getParent().getParent().getParent());
			});
		}
		
		this.summaries = $('reviews').getElements('.replies-summary');
		
		if(this.summaries.length > 0) {
			
			this.summaries.addEvent('click', function() {
				
				var replies = $(this).getParent().getElement('.replies');
				
				$(this).hide();
				$(replies).show();
				
				ReviewReply.fx.toElement($(replies));
			});
		}
	},
	
	show : function(parentId, attachTo) {
		
		if(parentId == 0)
			return;
			
		html = '<form action="" method="POST" onsubmit="return ReviewReply.submit(this);" data-parentid="' + parentId + '">';
		html += '<p class="label">Γράψε την απάντησή σου στο παραπάνω:</p>'
		html += '<textarea rows="6" columns="50" name="reply-descr" class="field"></textarea>';
		html += '<input type="submit" class="button" value="Αποστολή &raquo;">';
		html += '</form>';
		
		var form = $C('div').setClass('reply').setHTML(html).injectIn($(attachTo));
		
		this.fx.toElement($(form));
		
		$(form).getElement('textarea').focus();
	},
	
	submit : function(form) {
		
		var parameters = {
			'isAjax'	: true,
			'action'	: 'submitMerchantReply',
			'ak'		: window.User.ak,
			'parent-id'	: $(form).getProperty('data-parentid'),
			'reply-descr': $(form).getElement('textarea').getValue()
		};

		if(parameters['reply-descr'] == '') {
		
			alert('Πληκτρολόγησε μια απάντηση');
			$(form).getElement('textarea').focus();
			
			return false;
		}
		
		this.loading = true;
		
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{

				var response = this.responseJSON;

				ReviewReply.loading = false;
				
				if(parseInt(response.res.faultCode) > 0) {
				
					$(form).getParent().remove();

					if(parseInt(response.res.faultCode) == 403)
						LoginRegisterBox.loginRender(response.res.fwd, true);
					else						
						alert('Σφάλμα: ' + response.res.faultString);
							
					return;
				}
				
				$(form).getParent().remove();
				
				alert('Η απάντησή σου απεστάλη με επιτυχία! Το προσωπικό του BestPrice θα την αξιολογήσει και θα την ενεργοποιήσει μέσα στις επόμενες 24 ώρες.');
			},
		
			'parameters' : parameters
		
		}).send();		

		return false;
	}
}

ItemTour = {
	
	initialize : function() {
		
		if($('page-item')) {

			this.tour = new Tour([
				[$('#images-dots .zoom'), 			"Κάνε κλικ στο μεγεθυντικό φακό για να δεις την εικόνα σε μεγαλύτερη διάσταση."],
				[$('#have-want-container .have'), 	"Επίλεξε \"<strong>Το έχω</strong>\" σε προϊόντα που έχεις αποκτήσει, για να διαμορφώσεις την <a href=\"/user/#havelist\">αντίστοιχη λίστα</a>."],
				[$('#have-want-container .want'), 	"Επίλεξε \"<strong>Το θέλω</strong>\" αν θέλεις να αποκτήσεις το προϊόν, ώστε να μπει στην <a href=\"/user/#wishlist\">αντίστοιχη λίστα</a> και <strong>να λαμβάνεις ειδοποιήσεις μέσω email</strong> κάθε φορά που μειώνεται η τιμή του!"],
				[$('tab-nearby'), 					"Δες τα κοντινά σε εσένα καταστήματα που διαθέτουν αυτό το προϊόν."],
				[$('tab-reviews'), 					"Διάβασε τις αξιολογήσεις άλλων χρηστών ή αξιολόγησε ο ίδιος το προϊόν."]
			], { 'name' : 'item-page' });
		}

		if(($('page-cat') || $('page-search')) && $('results-main') && $('results-main').getElement('.compare-icon')) {

			this.tour = new Tour([
				[$('results-main').getElement('.compare-icon'), "Κάνε κλικ εδώ για να προσθέσεις το προϊόν στην λίστα σύγκρισης"]
			], { 'name' : 'compare-tour'});
		}
	},

	destructor : function() {
		
		this.tour && this.tour.finish(true);
	}
}

ImageZoomer = {
	
	initialize : function() {
		
		if(!$('#content'))
			return;

		this.elements = $('#content').getElements('.image-zoomer');

		if(this.elements.length == 0)
			return;

		this.elements.each(function() {
			
			var self 		= this;
			var parent 		= this.getParent();
			var imageAnchor	= $(parent).getElement('a');

			$(parent).addEvent('mouseenter', function() {
				
				var src 	= $(self).getProperty('data-fullsrc');
				var width 	= parseInt($(self).getProperty('data-fullwidth'));
				var height 	= parseInt($(self).getProperty('data-fullheight'));
				var href 	= $(imageAnchor).getProperty('href');
				var target  = $(imageAnchor).getProperty('rel');

				ImageZoomer.popup = $C('div').setStyles({
					'width'		: (width > 300 ? 300 : width),
					'height'	: (width > 300 ? 300 * height / width : height),
					'overflow'	: 'hidden',
					'position' 	: 'absolute',
					'bottom'	: '5px',
					'right'		: '80px',
					'z-index'	: 99999,
					'pointer-events' : 'none',
					'padding'	: '2px',
					'background': '#fff url(\'/css/img/spinner.gif\') no-repeat scroll center center',
					'border'	: '1px solid #e5e5e5',
					'box-shadow': '0px 1px 5px -1px rgba(0, 0, 0, .3)'
				}).setHTML('<a' + (typeof target == "string" ? ' rel="nofollow" target="_blank"' : '') + ' href="' + href + '"><img style=\"max-width:300px;\" src=\"' + src + '\"/></a>').injectIn(self);
			});
				
			$(parent).addEvent('mouseleave', function() {
				$(ImageZoomer.popup) && $(ImageZoomer.popup).remove();
				ImageZoomer.popup = null;
			});
		});

		return;

		this.elements.addEvent('mouseenter', function() {
			
			var src 	= $(this).getProperty('data-fullsrc');
			var width 	= parseInt($(this).getProperty('data-fullwidth'));
			var height 	= parseInt($(this).getProperty('data-fullheight'));

			ImageZoomer.popup = $C('div').setStyles({
				'width'		: (width > 300 ? 300 : width),
				'height'	: (width > 300 ? 300 * height / width : height),
				'overflow'	: 'hidden',
				'position' 	: 'absolute',
				'bottom'	: '5px',
				'right'		: '25px',
				'z-index'	: 99999,
				'padding'	: '2px',
				'background': '#fff url(\'/css/img/spinner.gif\') no-repeat scroll center center',
				'border'	: '1px solid #e5e5e5',
				'box-shadow': '0px 1px 5px -1px rgba(0, 0, 0, .3)'
			}).setHTML('<img style=\"max-width:300px;\" src=\"' + src + '\"/>').injectIn(this);
		});

		this.elements.addEvent('mouseleave', function() {
			$(ImageZoomer.popup) && $(ImageZoomer.popup).remove();
		});
	}
}

Pagelet = {
	
	'elements'	: '#filters a, #order-container a, .pagination a, .category-tree a, #trail a:not(:first-child)',

	initialize : function() {
		
		// Disable it for browsers that don't support pop state
		// so not to be mixed with the tab changes (product/user pages)
		if(!this.detectHistorySupport())
			return;

		// If there is already a hash fragment in the url
		// redirect user to the correct page and start from there
		if(location.hash && location.hash.split(/!/)[1])
			location = 'http://' + location.host + location.hash.split(/!/)[1];

		this.pageletLinks = $$(this.elements);

		if(this.pageletLinks.length == 0)
			return;

		// Disable pagelets for Compare page
		if($('page-compare'))
			return;

		this.loaded 		= (window.chrome || window.webkit ? false : true);
		this.previousURL 	= '';

		_dev && console.log('HISTORY SUPPORT: ' + this.detectHistorySupport());
		
		if(this.detectHistorySupport()) {

			this.currentUrl = location.href.replace("http://" + location.host, '');

            window.onpopstate = function(event) { 
	
				_dev && console.log('ON POP STATE CALLED', event);
		
				if((window.chrome || window.webkit) && !Pagelet.loaded) {
					
					_dev && console.log('ANOMALY DETECTED, BAILING OUT');
					Pagelet.loaded = true;

					return;
				}

				var newURL = location.href.replace("http://" + location.host, '');
				
				// If we just switch tabs in the same page, don't request a new URL

				if(newURL.indexOf('#') !== -1 && newURL.split(/#/)[0] == Pagelet.currentUrl.split(/#/)[0]) {
					
					_dev && console.log('SWITCHING TAB, SKIPPING...');
					Pagelet.currentUrl = newURL;
					
					return;
				}

				Pagelet.fetchNewURL(newURL);
				Pagelet.currentUrl = newURL;
			}

		} else {    
		    
		    // CURRENTLY OFFLINE
		    // For browsers without history support
		    // detect hash fragment change
			(function() {
			
			    if(!location.hash) {
			
					//When we go just 1 step before the fragment in history
					if(Pagelet.previousURL != "" && location.href.replace("http://" + location.host, '') !== Pagelet.previousURL) {

						var newURL = location.href.replace("http://" + location.host, '');
						
				        Pagelet.fetchNewURL(newURL);
				        Pagelet.previousURL = newURL;
					}
					
			        return;
			    }
			    
			    var newURL = location.hash.split(/!/)[1];
			    
			    if(newURL && newURL != '' && newURL != Pagelet.previousURL) {
			        
			        Pagelet.fetchNewURL(newURL);
			        Pagelet.previousURL = newURL;
			    }
			    
			}).periodical(100, this);
		}
		
		// Catch any silly external links ffs
		//_dev && window.addEvent("beforeunload", function() { return 'You are leaving this page, ok?'; });

		this.attachHandlers();
	},

	attachHandlers : function() {
		
		this.pageletLinks = $$(this.elements);
		
		this.pageletLinks.addEvent('click', function(event) {

			_dev && console.log('Click event', event);

			// When middle click / ctrl click / option click are enabled, do nothing
			if(event.middleClick || event.meta || event.ctrl || event.rightClick)
				return;
			
		    var element = event.target;
		    
		    // Catch the span elements that are nested inside a tags (<a><span>lala</span></a>)
		    if(element.nodeName.toLowerCase() != "a" && $(element).getParent() && $(element).getParent().nodeName.toLowerCase() == "a")
		    	element = $(element).getParent();
		        
		    var href    = $(element).getProperty('href');
		    var title   = $(element).innerHTML;
		    
			if(!href)
				return;
			
		    if(element.nodeName.toLowerCase() != "a" || href == "" || href.indexOf("javascript") >= 0)
		        return;
		    
		    if(href.indexOf("http") >= 0 && href.indexOf(window.location.host) == -1)
		        return;

		    // if there is already a Core event attached to it then ignore it
		    // if($(element).hasEvent('click')) {
			//	_dev && console.log('element has already a click event attached!', element.events);
		    //    return;
			//}

		    event.preventDefault();
			
			_dev && console.log('CHANGING TO: ' + href);

		    Pagelet.changeURL(href, title); 
		});

	},

    detectHistorySupport: function() { return !!(window.history && history.pushState); },
   
    changeURL : function(href, title) {
        
    	var relativePath = (href.indexOf("http") == 0 ? href.replace("http://" + window.location.host, '') : href);

		_dev && console.log('changeURL called', href, relativePath);
		
        if(this.detectHistorySupport()) {
	
            window.history.pushState('', title, relativePath);
			this.fetchNewURL(relativePath);
			this.currentUrl = relativePath;
			
        } else { 
			
			// Move relative path to hash fragment
            window.location.hash = '#!' + relativePath;

			// If we explicitly want to load the same url again, then load it here
			if(this.previousURL == relativePath)
				this.fetchNewURL(relativePath);
		}
    },

	fetchNewURL : function(newURL) {

		$('wrapper').addClass('loading');

		_dev && console.log('FETCHING: ' + newURL);
        
        new Ajax('get', {
            
            'url'		: '/tools/pagelet.php',
            'parameters': { 'path' : newURL },
            
            onSuccess   : function(result) {

                var response = result.responseJSON;

				_dev && console.log('Received response: ', response, result.responseText);

				$('wrapper').removeClass('loading');
		
				if(response && response.html && response.html != '') {

					//Scroll to top
					document.body.scrollTop = document.documentElement.scrollTop = 0;

					document.body.id = 'page-' + response.bodyId;
                   
					//Change the title
					_dev && console.log('New title:', response.title);

					if(response.title)
						document.title = response.title;

                    // Inject the data
                    $('wrapper').setHTML(response.html);
                    
                    $(document.body).setClass((response.classTitle ? response.classTitle : ''));

					// Move to the top of page
					document.body.scrollTop = 0;
					
                    // eval all scripts in order to get some js variables from the dump
					var allScripts = $('wrapper').getElements('script');
					
					if(allScripts.length > 0) {
						
	                    allScripts.each(function(element, index) { 
	
							_dev && console.log('EVALUATING SCRIPT:', this.innerHTML);
							
							eval(this.innerHTML);
						
							// RE-Init all objects after evaluating the last script
							if(index == allScripts.length - 1) {
								
								_dev && console.log('Initializing Objects 1');
								
								Pagelet.initAll();
							}
						});
					} else {
						
						_dev && console.log('Initializing Objects 2');

						Pagelet.initAll();
					}
					
                } else
					_dev && console.log('OOPS MALFORMED RESPONSE!');
            }
            
        }).send();
    },

    initAll : function() {
    	
    	_dev && console.log('init');

  		// Now -ideally- we would call the destructors of each Object here
  		ItemTour.destructor();

    	document.getElements('header,footer').each(function() { this.removeEvents(); });

    	this.attachHandlers();

		Objects.each(function() { 

			if(this.timerId)
				clearTimeout(this.timerId);

			this.initialize();
		});

		if(typeof Admin != 'undefined')
			Admin.refresh && Admin.refresh();
    }
}

SantaTerms = {
	
	initialize : function() {
		
		if(!$('santa-terms'))
			return;

		this.overlay = new Overlay('', {

			'duration'	: 400,
			'className'	: 'overlay',
			'onOpen'	: function() 	{ this.element.addClass('overlay-normal'); },
			'beforeClose': function() 	{ this.element.removeClass('overlay-normal'); }
	   	});
	
		$('santa-terms').addEvent('click', function() { SantaTerms.showModal(this); });
	},
	
	showModal : function(element) {
		
		this.element = element;
		
		this.cid = parseInt($(element).getProperty('data-cid'));

		var name = $(element).getProperty('data-name');		
		var html = [];

		html.push('<div class="overlay-inner">');

		html.push('<div class="overlay-header">');
		html.push('<h4>Όροι συμμετοχής στην κλήρωση<span class="close" onclick="SantaTerms.overlay.close();">x</span></h4>');
		html.push('</div>');
		html.push('<div style="height:500px;overflow-y:auto;" class="overlay-body clr">');
		html.push(santaTerms);
		html.push('</div>');	
		html.push('</div>');

		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();
	}
}

UserFeed = {
	
	initialize : function() {
		
		if(!$('page-stream'))
			return;

		this.interval= 10000;
		this.timerId = this.fetch.periodical(this.interval, this);

		this.fetch();
	},

	fetch : function() {
		
		var firstElement= $('page-stream').getElement('ul.stream li');
		var lastId 		= parseInt(firstElement.getProperty('data-sid'));
		var parameters 	= {
			'action' 	: 'getMoreEvents',
			'isAjax'	: true,
			'lastid'	: lastId
		};
	
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				if(parseInt(response.res.faultCode) > 0)
					return;

				if(!response.res.html)
					return;

				if(response.res.html == "")
					return;

				response.res.html.injectBefore(firstElement);

				var elements = $('page-stream').getElements('ul.stream li');

				for(var i = 0; i < response.res.count; i++)
					new Fx.Style(elements[i], 'backgroundColor', { 'duration' : 1000 }).start('#FFFFCC', '#FFFFFF');

				for(var i = elements.length - response.res.count; i < elements.length; i++)
					elements[i].remove();

				elements[elements.length - response.res.count - 1].addClass('bottom');
			},
		
			'parameters' : parameters
		
		}).send();

		// Refresh dates on elements
		this.refreshDates();
	},

	refreshDates : function() {
		
		$('page-stream').getElements('ul.stream li').each(function() {

			var dtElement 	= $(this).getElement('.dt');
			var date 		= new Date(parseInt($(dtElement).getProperty('data-ts')) * 1000);

			$(dtElement).setHTML(date.dt());
		});
	}
}

SubTabs = {
	
	initialize : function() {
		
		if(!$('sub-tabs'))
			return;

		this.boxes 	= $('sub-tabs').getParent().getElements('.sub-tab');
		this.tabs 	= $('sub-tabs').getElements('a');

		this.tabs.addEvent('click', function() {
			
			var tab = $(this).getProperty('data-subtab');

			SubTabs.tabs.each(function() { this.getParent().removeClass('selected'); });
			SubTabs.boxes.each(function() { this.hide(); });

			$('sub-' + tab).show();
			this.getParent().addClass('selected');
		});
	}
}

OverlayOpener = {
	
	initialize : function() {
		
		if(!$('have-overlay-opener') && !$('want-overlay-opener'))
			return;

		this.pg 		= 1;
		this.perPage	= 20;
        this.overlay 	= new Overlay('', {
			'duration'	: 400,
			'className'	: 'overlay',
			'onOpen'	: function() {

				this.element.addClass('overlay-normal');
			},
			'beforeClose': function() {

				this.element.removeClass('overlay-normal');
			}
        });

        this.lid = parseInt($('content').getProperty('data-lid'));

		$('have-overlay-opener') && $('have-overlay-opener').addEvent('click', function() { OverlayOpener.fetch(1); });
		$('want-overlay-opener') && $('want-overlay-opener').addEvent('click', function() { OverlayOpener.fetch(0); });
	},

	fetch : function(wantOrHave) {
		
		var parameters = {
			'action' 	: 'getFriends',
			'wantOrHave': wantOrHave,
			'isAjax'	: true,
			'ak'		: window.User.ak,
			'pg'		: this.pg,
			'perPage'	: this.perPage,
			'lid'		: this.lid
		};
	
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				if(parseInt(response.res.faultCode) > 0)
					alert('Σφάλμα: ' + response.res.faultString);
				else
					OverlayOpener.render(response.res, wantOrHave);
			},
		
			'parameters' : parameters
		
		}).send();
	},

	render : function(response, wantOrHave) {

		var html = [];

		html.push('<div class="overlay-inner">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Φίλοι σου που ' + (wantOrHave == 0 ? 'θέλουν' : 'έχουν') + ' το προϊόν (' + response.total + ')<span class="close" onclick="OverlayOpener.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body clr">');

		if(response.total > 0)
			html.push('<ul class=\"users-list clr\">');

		html.push(response.html);

		if(response.total > 0)
			html.push('</ul>');

		if(response.count < response.total) {
			
        	html.push('<div class="user-pagination clr">');

        	if(this.pg > 1)
	            html.push('<a href="javascript:void(0);" onclick="OverlayOpener.prev(' + wantOrHave + ')">&laquo;</a>');

			html.push(' Σελίδα ' + this.pg + '/' + Math.ceil(response.total / this.perPage) + ' ');

			if(this.pg < Math.ceil(response.total / this.perPage))
				html.push('<a href="javascript:void(0);" onclick="OverlayOpener.next(' + wantOrHave + ')">&raquo;</a>');

			html.push('</div>');
		}

		html.push('</div>');	
		html.push('</div>');
		
		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();	
	},

	prev : function(wantOrHave) {
		
		if(this.pg == 1)
			return;

		this.pg--;
		this.fetch(wantOrHave);
	},

	next : function(wantOrHave) {
		
		this.pg++;
		this.fetch(wantOrHave);
	}
}

FilterWishlist = {

	'regs' : {},

	initialize : function() {
		
		if(!$('filter-wishlist'))
			return;

		this.elements 	= $('wishlist').getElements('table tr h4');
		this.q 			= '';

		$('filter-wishlist').addEvent('submit', function(event) { event.stop(); return false; });
		$('filter-wishlist').getElement('input').addEvent('keyup', function(event) {
		
			if(event.code == 27)
				$(this).setValue('');

			var text = $(this).getValue();
			
			FilterWishlist.q = text;
			FilterWishlist.filter(text);
		});
		$('filter-wishlist').getElement('input').addEvent('click', function(event) {

			var text = $(this).getValue();
			
			FilterWishlist.q = text;
			FilterWishlist.filter(text);
		});

		this.sortOptions = $('wishlist').getElements('.sort-choices ul a');

		if(this.sortOptions.length == 0)
			return;

		this.sortNumber = 0;
		this.elements.each(function() { this._row = this.getParent().getParent(); });

		this.sortOptions.addEvent('click', function(event) {
			
			event.stop();

			var sort = parseInt(this.getProperty('data-sort'));

			if(FilterWishlist.sortNumber == sort)
				return;

			FilterWishlist.sortNumber = sort;

			FilterWishlist.sortOptions.each(function() {
				
				if(parseInt(this.getProperty('data-sort')) == FilterWishlist.sortNumber)
					this.getParent().addClass('selected');
				else
					this.getParent().removeClass('selected');
			});		

			FilterWishlist.sortElements(sort);
		});
	},

	sortDate  : function(a, b) { return (parseInt(a._row.getProperty('data-ts')) < parseInt(b._row.getProperty('data-ts')) ? 1 : (parseInt(a._row.getProperty('data-ts')) > parseInt(b._row.getProperty('data-ts')) ? -1 : 0)); },
	sortPrice : function(a, b) { return (parseInt(a._row.getProperty('data-price')) > parseInt(b._row.getProperty('data-price')) ? 1 : (parseInt(a._row.getProperty('data-price')) < parseInt(b._row.getProperty('data-price')) ? -1 : 0)); },
	sortTitle : function(a, b) { return a._row.getProperty('data-title').localeCompare(b._row.getProperty('data-title')); },

	sortElements : function(sortNumber) {
		
		switch(sortNumber) {
			
			case 0 :
				this.elements.sort(this.sortDate);
			break;

			case 1 :
				this.elements.sort(this.sortPrice);
			break;

			case 2 :
				this.elements.sort(this.sortTitle);
			break;
		}
	
		$('wishlist').getElement('tbody').setHTML('');

		var shownFirst = false;

		this.elements.each(function(element, index) {
			
			if((FilterWishlist.q == '' && index == 0) || (FilterWishlist.q != '' && !shownFirst && this._row.hasClass('shown'))) {

				this._row.addClass('first');

				if(FilterWishlist.q != '')
					shownFirst = true;

			} else
				this._row.removeClass('first');

			this._row.injectIn($('wishlist').getElement('tbody'));
		});
	},

	filter : function(text) {

		text 		= text.trim();
		var reg 	= this.regs[text] || new RegExp('(' + text.escapeRegExp() + ')', 'gi'),
			
		hidden 		= 0;

		this.elements.each(function(element) {

			element._row = element._row || element.getParent().getParent();
			element._row.removeClass('first');

			FilterWishlist.format(element, reg);
			
			if(text === '' || element.getText().match(reg)) {

				element._row.show().addClass('shown');

			} else {
				hidden++;
				element._row.hide().removeClass('shown');
			}
		});

		$('wishlist').getElements('table tr.shown')[0] && $('wishlist').getElements('table tr.shown')[0].addClass('first');

		if (hidden === this.elements.length)
			this.noResults();
		else if(this.noResultsRow) {

			this.noResultsRow.remove();
			this.noResultsRow= null;
		}
	},

	noResults 	: function () {
		
		if(this.noResultsRow)
			return this;

		this.noResultsRow = $C('tr').addClass('first').injectIn($('#wishlist table tbody')).
		setHTML('<td style="text-align: center;">Δεν βρέθηκαν προϊόντα που να περιέχουν την λέξη που αναζητάς</td>');
	},

	format : function(element, reg, init) {
		
		element._link = element._link || element.getFirst();

		if(!element._original)
			element._original = element._link.innerHTML;
		
		element._link.innerHTML = element._original;
		
		var _new = element._link.innerHTML.replace(reg, '<b>$1</b>');

		element._link.innerHTML = element._original.replace(reg, '<b>$1</b>');
	}
}

BBSlideshow = {

	initialize : function() {
		
		if(!$('start-slideshow'))
			return;
		
		if(window.ie6 || window.ie7) {

			$('start-slideshow').remove();
			return;
		}

		this.pg 		= 0;
		this.activePhoto= 0;	
		this.loading 	= false;
		this.enabled 	= false;
		this.photos 	= [];
		this.cid 		= parseInt($('start-slideshow').getProperty('data-cid'));

		$('start-slideshow').addEvent('click', this.begin.bind(this));
	
		if(window.ios) {
		
			window.scrollTo(0,0);
			
			window.addEventListener("orientationchange", function(event) {
			
				if(!BBSlideshow.enabled)
					return;

				window.scrollTo(0, 0);
				
			}, false);
			
			document.addEventListener("touchstart", function(event) { 
		
				if(!BBSlideshow.enabled)
					return;

				BBSlideshow.startX = event.touches[0].pageX; 	

			}, false);
		
			document.addEventListener("touchmove", function(event) {
	
				if(!BBSlideshow.enabled)
					return;

				event.preventDefault();

				BBSlideshow.curX = event.targetTouches[0].pageX - BBSlideshow.startX;
			
			}, false);

			document.addEventListener("touchend", function(event) {
	
				if(!BBSlideshow.enabled)
					return;

				event.preventDefault();
			
				if(BBSlideshow.curX < 0)
					BBSlideshow.getNext();
				else if(BBSlideshow.curX > 0)
					BBSlideshow.getPrevious();
				
			}, false);
		}

		document.addEvent('keydown', function(event) {
	
			if(!BBSlideshow.enabled)
				return;

			if(event.code == 13) {
				
				window.location = BBSlideshow.photos[BBSlideshow.activePhoto].link;
				return;
			}

			if(event.code == 27) {

				event.stop();
				BBSlideshow.reset();
			}
			
			if(event.code == 37) {
			
				event.stop();
				BBSlideshow.getPrevious();
			}
		
			if(event.code == 39) {
			
				event.stop();
				BBSlideshow.getNext();
			}
		});
	
		window.addEvent('resize', this.resize.bind(this));
		
		this.arrowsDefined = true;
	},
	
	begin : function() {
		
		var windowWidth = window.getWidth(), windowHeight = window.getHeight();
		
		this.enabled 	= true;
		
		document.documentElement.setStyle('overflow', 'hidden');

		this.element = $C('div').setClass('bbslide-container').injectIn(document.body);

		if(document.documentElement.webkitRequestFullScreen) {
				
			document.documentElement.webkitRequestFullScreen();
			document.documentElement.onwebkitfullscreenchange = function (event) {

				if(!document.webkitIsFullScreen)
					BBSlideshow.reset();
			};
		}

		if(document.documentElement.mozRequestFullScreen) {
				
			document.documentElement.mozRequestFullScreen();
			document.onmozfullscreenchange = function() {

				if(!document.mozFullScreen)
					BBSlideshow.reset();
			};
		}

		this.leftImage = $C('div').setClass('sec-image').setStyles({
			'top'				: (5 * windowHeight / 20),
			'left'				: (- (5 * windowWidth / 10) / (window.ios ? 2 : 3)),
			'width'				: (5 * windowWidth / 10),
			'height'			: (5 * windowHeight / 10)
		}).injectIn(this.element).hide().addEvent('click', this.getPrevious.bind(this));

		this.rightImage = $C('div').setClass('sec-image').setStyles({
			'top'				: (5 * windowHeight / 20),
			'right'				: (- (5 * windowWidth / 10) / (window.ios ? 2 : 3)),
			'width'				: (5 * windowWidth / 10),
			'height'			: (5 * windowHeight / 10)
		}).injectIn(this.element).hide().addEvent('click', this.getNext.bind(this));

		this.blurLayer = $C('div').setClass('blur-layer').injectIn(this.element);

		this.mainPhoto = $C('div').setClass('main-photo').setStyles({
			'top'				: (3 * windowHeight / 20),
			'left'				: (3 * windowWidth / 20),
			'width'				: (7 * windowWidth / 10),
			'height'			: (7 * windowHeight / 10)
		}).injectIn(this.element);

		this.imageContainer = $C('div').setStyles({
			'position'			: 'relative',
			'width'				: '100%',
			'height'			: '100%'
		}).injectIn(this.mainPhoto);

		this.titleElement = $C('h1').setClass('title').setStyles({
			'width'				: (7 * windowWidth / 10 - 20)
		}).injectIn(this.mainPhoto).hide();

		this.features = $C('div').setClass('descr').setStyles({
			'width'				: (7 * windowWidth / 10 - 20)
		}).injectIn(this.mainPhoto).hide();

		this.price = $C('div').setClass('price').injectIn(this.mainPhoto).hide();

		this.closeButton = $C('a').setClass('close').setHTML((window.ie ? "x" : '&#10005;')).injectIn(this.mainPhoto).addEvent('click', function() {

			if(document.documentElement.webkitRequestFullScreen)
				document.webkitCancelFullScreen();

			if(document.documentElement.mozRequestFullScreen) 
				document.mozCancelFullScreen();

			BBSlideshow.reset();
		});

		this.leftArrow = $C('a').setClass('arrow').setHTML((window.ie ? "<" : "&#9664;")).setStyles({
			'left'			: (3 * windowWidth / 20 - 30),
			'top'			: (3 * windowHeight / 20),
			'line-height'	: (7 * windowHeight / 10),
			'height'		: (7 * windowHeight / 10)
		}).injectIn(this.element).addEvent('click', this.getPrevious.bind(this)).hide();

		this.rightArrow = $C('a').setClass('arrow').setHTML((window.ie ? ">" : "&#9654;")).setStyles({
			'right'			: (3 * windowWidth / 20 - 30),
			'top'			: (3 * windowHeight / 20),
			'line-height'	: (7 * windowHeight / 10),
			'height'		: (7 * windowHeight / 10)
		}).injectIn(this.element).addEvent('click', this.getNext.bind(this)).hide();
		
		if(window.ie8) {
			
			this.rightArrow.setStyle('color', '#333');
			this.leftArrow.setStyle('color', '#333');
		}

		this.getPhotos();
	},
	
	reset : function() {
		
		this.element.remove();
		
		document.documentElement.setStyle('overflow', 'visible');

		this.pg 			= 0;
		this.photos 		= [];
		this.activePhoto 	= 0;
		this.enabled 		= false;
	},
	
	getPhotos : function() {

		if(this.loading)
			return;

		this.loading = true;	

		var parameters = {
			'action' 	: 'slideshowImages',
			'isAjax'	: true,
			'catid'		: this.cid,
			'pg'		: (this.pg + 1)
		};
	
		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{
			
				var response = this.responseJSON;

				BBSlideshow.loading = false;

				if(parseInt(response.res.faultCode) > 0) {

					if(BBSlideshow.pg == 0) {

						alert('Σφάλμα: ' + response.res.faultString);
						BBSlideshow.reset();
					}

					return;
				}

				if(!response.res)
					return;
				
				if(response.res == 0) {

					if(BBSlideshow.pg == 0)
						BBSlideshow.reset();

					return;
				}

				BBSlideshow.updatePhotos(response.res);
			},
		
			'parameters' : parameters
		
		}).send();
	},
	
	updatePhotos : function(photos) {
		
		if(photos.length == 0)
			return;
			
		this.photos = this.photos.concat(photos);

		this.setActivePhoto();
	},
	
	setActivePhoto : function() {
		
		if(!this.photos[this.activePhoto])
			return;
			
		var activePhoto = this.photos[this.activePhoto];

		if(this.activePhoto == 0)
			this.leftArrow.hide();
		else
			this.leftArrow.show();

		if(this.activePhoto == this.photos.length -1)
			this.rightArrow.hide();
		else
			this.rightArrow.show();

		if(this.activePhoto > 0)
			this.leftImage.setHTML('<img style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; display: block; margin: auto;" src="' + this.photos[this.activePhoto - 1].photo_url + '"/>').show();
		else
			this.leftImage.hide();

		this.imageContainer.setHTML('<a href="' + activePhoto.link + '"><img style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; display: block; margin: auto;" src="' + activePhoto.photo_url + '"/></a>');

		this.titleElement.setHTML('<a href="' + activePhoto.link + '">' + activePhoto.title + '</a>').show();
		
		if(activePhoto.descr)
			this.features.setHTML(activePhoto.descr).show();
		else
			this.features.setHTML('').hide();

		this.price.setHTML('<span><a href="' + activePhoto.link + '">' + activePhoto.price + '</a></span><em>' + activePhoto.merchant + '</em>').show();

		if(this.activePhoto < this.photos.length - 1)
			this.rightImage.setHTML('<img style="position: absolute; top: 0; left: 0; right: 0; bottom: 0; display: block; margin: auto;" src="' + this.photos[this.activePhoto + 1].photo_url + '""/>').show();
		else
			this.rightImage.hide();
	},
	
	resize : function() {
		
		if(!this.enabled)
			return;

		var maxWidth 	= window.getWidth();
		var maxHeight 	= window.getHeight();
		
		this.mainPhoto.setStyles({
			'top'				: (3 * maxHeight / 20),
			'left'				: (3 * maxWidth / 20),
			'width'				: (7 * maxWidth / 10),
			'height'			: (7 * maxHeight / 10)
		});

		this.leftImage.setStyles({
			'top'				: (5 * maxHeight / 20),
			'left'				: (- (5 * maxWidth / 10) / (window.ios ? 2 : 3)),
			'width'				: (5 * maxWidth / 10),
			'height'			: (5 * maxHeight / 10)
		});

		this.rightImage.setStyles({
			'top'				: (5 * maxHeight / 20),
			'right'				: (- (5 * maxWidth / 10) / (window.ios ? 2 : 3)),
			'width'				: (5 * maxWidth / 10),
			'height'			: (5 * maxHeight / 10)
		});

		this.leftArrow.setStyles({
			'left'			: (3 * maxWidth / 20 - 30),
			'top'			: (3 * maxHeight / 20),
			'line-height'	: (7 * maxHeight / 10),
			'height'		: (7 * maxHeight / 10)
		});

		this.rightArrow.setStyles({
			'right'			: (3 * maxWidth / 20 - 30),
			'top'			: (3 * maxHeight / 20),
			'line-height'	: (7 * maxHeight / 10),
			'height'		: (7 * maxHeight / 10)
		});

		this.features.setStyles({
			'width'	: (7 * maxWidth / 10 - 20)
		});

		this.titleElement.setStyles({
			'width'	: (7 * maxWidth / 10 - 20)
		});
	},
	
	getNext : function() {

		if(this.activePhoto == this.photos.length - 1)
			return;

		if(this.activePhoto == this.photos.length - 5 && typeof this.photos[this.activePhoto + 5] == 'undefined') {

			this.pg++;
			this.getPhotos();
		}
		
		this.activePhoto++;
		this.setActivePhoto();
	},
	
	getPrevious : function() {
		
		if(this.activePhoto == 0)
			return;
		
		this.activePhoto--;
		this.setActivePhoto();		
	}
}

CartMachine = {

	'eligibleMids'	: [209, 173, 497, 897, 118, 543],
	'countries'		: {
		// 'AL' : 'Albania',
		// 'DZ' : 'Algeria',
		// 'AS' : 'American Samoa',
		// 'AD' : 'Andorra',
		// 'AO' : 'Angola',
		// 'AI' : 'Anguilla',
		// 'AQ' : 'Antarctica',
		// 'AG' : 'Antigua and Barbuda',
		// 'AR' : 'Argentina',
		// 'AM' : 'Armenia',
		// 'AW' : 'Aruba',
		// 'AU' : 'Australia',
		// 'AT' : 'Austria',
		// 'AZ' : 'Azerbaijan',
		// 'BS' : 'Bahamas, The',
		// 'BH' : 'Bahrain',
		// 'BD' : 'Bangladesh',
		// 'BB' : 'Barbados',
		// 'BY' : 'Belarus',
		// 'BE' : 'Belgium',
		// 'BZ' : 'Belize',
		// 'BJ' : 'Benin',
		// 'BM' : 'Bermuda',
		// 'BT' : 'Bhutan',
		// 'BO' : 'Bolivia',
		// 'BQ' : 'Bonaire, Saint Eustatius and Saba',
		// 'BA' : 'Bosnia and Herzegovina',
		// 'BW' : 'Botswana',
		// 'BV' : 'Bouvet Island',
		// 'BR' : 'Brazil',
		// 'IO' : 'British Indian Ocean Territory',
		// 'BN' : 'Brunei Darussalam',
		// 'BG' : 'Bulgaria',
		// 'BF' : 'Burkina Faso',
		// 'BI' : 'Burundi',
		// 'KH' : 'Cambodia',
		// 'CM' : 'Cameroon',
		// 'CA' : 'Canada',
		// 'CV' : 'Cape Verde',
		// 'KY' : 'Cayman Islands',
		// 'CF' : 'Central African Republic',
		// 'TD' : 'Chad',
		// 'CL' : 'Chile',
		// 'CN' : 'China',
		// 'CX' : 'Christmas Island',
		// 'CC' : 'Cocos (Keeling) Islands',
		// 'CO' : 'Colombia',
		// 'KM' : 'Comoros',
		// 'CG' : 'Congo',
		// 'CD' : 'Congo, Democratic Republic of',
		// 'CK' : 'Cook Islands',
		// 'CR' : 'Costa Rica',
		// 'HR' : 'Croatia',
		// 'CW' : 'Curaçao',
		'CY' : 'Κύπρος',
		// 'CZ' : 'Czech Republic',
		// 'DK' : 'Denmark',
		// 'DJ' : 'Djibouti',
		// 'DM' : 'Dominica, Commonwealth of',
		// 'DO' : 'Dominican Republic',
		// 'TL' : 'East Timor',
		// 'EC' : 'Ecuador',
		// 'EG' : 'Egypt',
		// 'SV' : 'El Salvador',
		// 'GQ' : 'Equatorial Guinea',
		// 'ER' : 'Eritrea',
		// 'EE' : 'Estonia',
		// 'ET' : 'Ethiopia',
		// 'FK' : 'Falkland Islands',
		// 'FO' : 'Faroe Islands',
		// 'FJ' : 'Fiji',
		// 'FI' : 'Finland',
		// 'FR' : 'France',
		// 'GF' : 'French Guiana',
		// 'PF' : 'French Polynesia',
		// 'TF' : 'French Southern Territories',
		// 'GA' : 'Gabon',
		// 'GM' : 'Gambia, The',
		// 'GE' : 'Georgia',
		// 'DE' : 'Germany',
		// 'GH' : 'Ghana',
		// 'GI' : 'Gibraltar',
		'GR' : 'Ελλάδα',
		// 'GL' : 'Greenland',
		// 'GD' : 'Grenada',
		// 'GP' : 'Guadeloupe',
		// 'GU' : 'Guam',
		// 'GT' : 'Guatemala',
		// 'GG' : 'Guernsey',
		// 'GN' : 'Guinea',
		// 'GW' : 'Guinea-Bissau',
		// 'GY' : 'Guyana',
		// 'HT' : 'Haiti',
		// 'HM' : 'Heard Island and the McDonald Islands',
		// 'VA' : 'Holy See',
		// 'HN' : 'Honduras',
		// 'HK' : 'Hong Kong',
		// 'HU' : 'Hungary',
		// 'IS' : 'Iceland',
		// 'IN' : 'India',
		// 'ID' : 'Indonesia',
		// 'IM' : 'Isle of Man',
		// 'IL' : 'Israel',
		// 'IT' : 'Italy',
		// 'CI' : 'Ivory Coast (Côte D\'ivoire)',
		// 'JM' : 'Jamaica',
		// 'JP' : 'Japan',
		// 'JE' : 'Jersey',
		// 'JO' : 'Jordan',
		// 'KZ' : 'Kazakhstan',
		// 'KE' : 'Kenya',
		// 'KI' : 'Kiribati',
		// 'KR' : 'Korea, Republic of',
		// 'KW' : 'Kuwait',
		// 'KG' : 'Kyrgyzstan',
		// 'LA' : 'Lao, People\'s Democratic Republic',
		// 'LV' : 'Latvia',
		// 'LB' : 'Lebanon',
		// 'LS' : 'Lesotho',
		// 'LR' : 'Liberia',
		// 'LY' : 'Libya',
		// 'LI' : 'Liechtenstein',
		// 'LT' : 'Lithuania',
		// 'LU' : 'Luxembourg',
		// 'MO' : 'Macao',
		// 'MK' : 'FYROM',
		// 'MG' : 'Madagascar',
		// 'MW' : 'Malawi',
		// 'MY' : 'Malaysia',
		// 'MV' : 'Maldives',
		// 'ML' : 'Mali',
		// 'MT' : 'Malta',
		// 'MH' : 'Marshall Islands',
		// 'MQ' : 'Martinique',
		// 'MR' : 'Mauritania',
		// 'MU' : 'Mauritius',
		// 'YT' : 'Mayotte',
		// 'MX' : 'Mexico',
		// 'FM' : 'Micronesia, Federated States of',
		// 'MD' : 'Moldova, Republic of',
		// 'MC' : 'Monaco',
		// 'MN' : 'Mongolia',
		// 'ME' : 'Montenegro',
		// 'MS' : 'Montserrat',
		// 'MA' : 'Morocco',
		// 'MZ' : 'Mozambique',
		// 'MM' : 'Myanmar',
		// 'NA' : 'Namibia',
		// 'NR' : 'Nauru',
		// 'NP' : 'Nepal',
		// 'NL' : 'Netherlands',
		// 'AN' : 'Netherlands Antilles',
		// 'NC' : 'New Caledonia',
		// 'NZ' : 'New Zealand',
		// 'NI' : 'Nicaragua',
		// 'NE' : 'Niger',
		// 'NG' : 'Nigeria',
		// 'NU' : 'Niue',
		// 'NF' : 'Norfolk Island',
		// 'MP' : 'Northern Mariana Islands',
		// 'NO' : 'Norway',
		// 'OM' : 'Oman',
		// 'PK' : 'Pakistan',
		// 'PW' : 'Palau',
		// 'PA' : 'Panama',
		// 'PG' : 'Papua New Guinea',
		// 'PY' : 'Paraguay',
		// 'PE' : 'Peru',
		// 'PH' : 'Philippines',
		// 'PN' : 'Pitcairn',
		// 'PL' : 'Poland',
		// 'PT' : 'Portugal',
		// 'PR' : 'Puerto Rico',
		// 'QA' : 'Qatar',
		// 'IE' : 'Republic of Ireland',
		// 'RE' : 'Reunion',
		// 'RO' : 'Romania',
		// 'RU' : 'Russian Federation',
		// 'RW' : 'Rwanda',
		// 'SH' : 'Saint Helena',
		// 'KN' : 'Saint Kitts and Nevis',
		// 'LC' : 'Saint Lucia',
		// 'PM' : 'Saint Pierre and Miquelon',
		// 'VC' : 'Saint Vincent and The Grenadines',
		// 'WS' : 'Samoa',
		// 'SM' : 'San Marino',
		// 'ST' : 'Sao Tome and Principe',
		// 'SA' : 'Saudi Arabia',
		// 'SN' : 'Senegal',
		// 'RS' : 'Serbia',
		// 'SC' : 'Seychelles',
		// 'SL' : 'Sierra Leone',
		// 'SG' : 'Singapore',
		// 'SX' : 'Sint Maarten',
		// 'SK' : 'Slovakia',
		// 'SI' : 'Slovenia',
		// 'SB' : 'Solomon Islands',
		// 'SO' : 'Somalia',
		// 'ZA' : 'South Africa',
		// 'GS' : 'South Georgia and the South Sandwich Islands',
		// 'ES' : 'Spain',
		// 'LK' : 'Sri Lanka',
		// 'SR' : 'Suriname',
		// 'SJ' : 'Svalbard and Jan Mayen',
		// 'SZ' : 'Swaziland',
		// 'SE' : 'Sweden',
		// 'CH' : 'Switzerland',
		// 'TW' : 'Taiwan',
		// 'TJ' : 'Tajikistan',
		// 'TZ' : 'Tanzania, United Republic of',
		// 'TH' : 'Thailand',
		// 'TG' : 'Togo',
		// 'TK' : 'Tokelau',
		// 'TO' : 'Tonga',
		// 'TT' : 'Trinidad and Tobago',
		// 'TN' : 'Tunisia',
		// 'TR' : 'Turkey',
		// 'TM' : 'Turkmenistan',
		// 'TC' : 'Turks and Caicos Islands',
		// 'TV' : 'Tuvalu',
		// 'UG' : 'Uganda',
		// 'UA' : 'Ukraine',
		// 'AE' : 'United Arab Emirates',
		// 'GB' : 'United Kingdom',
		// 'US' : 'United States',
		// 'UM' : 'United States Minor Outlying Islands',
		// 'UY' : 'Uruguay',
		// 'UZ' : 'Uzbekistan',
		// 'VU' : 'Vanuatu',
		// 'VE' : 'Venezuela',
		// 'VN' : 'Vietnam',
		// 'VG' : 'Virgin Islands, British',
		// 'VI' : 'Virgin Islands, US',
		// 'WF' : 'Wallis and Futuna',
		// 'EH' : 'Western Sahara',
		// 'YE' : 'Yemen',
		// 'ZM' : 'Zambia',
		// 'ZW' : 'Zimbabwe'
	},

	initialize : function() {
		
		if(!_dev)
			return;

		if(!$('inner-header'))
			return;

		// Initialize cart structure
		this.cartStruct = {
			'user'		: {},
			'products' 	: {}	
		};

		this.flash = false;

		this.loadCart();

		this.scanAndAttach();
		this.updateCartIcon();

		this.readHashAndRender();
	},

	loadCart : function() {
		
		// Read the cart from localStorage or Cookie
		if(!window.safari && typeof localStorage != 'undefined' && typeof localStorage['cart'] != 'undefined' && localStorage['cart'] != null)
			this.cartStruct = JSON.parse(localStorage['cart']);
		else if(Cookie.get('cart') && Cookie.get('cart') != "")	
			this.cartStruct = JSON.parse(Cookie.get('cart'));
	},

	scanAndAttach : function() {
		
		if(!$('prices'))
			return;

		var tableCells = $('prices').getElements('tbody .price-tag');

		if(tableCells.length == 0)
			return;

		tableCells.each(function() { CartMachine.attachCartHandler(this); });
	},

	enumCart : function() { 

		if(typeof this.cartStruct == 'undefined' || this.cartStruct == null)
			return 0;

		var length = 0; 

		for(i in this.cartStruct.products)
			length += this.cartStruct.products[i].q;

		return length;
	},

	attachCartHandler : function(priceTagElement) {
	
		var mid = parseInt($(priceTagElement).getProperty('data-mid'));

		if(this.eligibleMids.indexOf(mid) === -1)
			return;

		var id = parseInt($(priceTagElement).getProperty('data-refid'));

		if(id == 0 || isNaN(id))
			return;

		var exists = (typeof this.cartStruct.products[id] != "undefined");

		if($(priceTagElement).cartElement) {
			
			if(exists) {

				$(priceTagElement).cartElement && $(priceTagElement).cartElement
																	.setProperty('title', 'Αφαίρεση από το καλάθι αγορών')
																	.addClass('added')
																	.setHTML('-');	
			} 

			return;
		}

		$(priceTagElement).addClass('cart-enabled');

		var productRow 		= $(priceTagElement).getParent().getParent();
		var productStruct 	= {
			'q' 			: 1,
			'isGift'		: false,
			'priceNum'		: parseInt($(priceTagElement).getProperty('data-price')),
			'title'			: ($(productRow).getElement('.descr a').innerText ? $(productRow).getElement('.descr a').innerText : $(productRow).getElement('.descr a').textContent),
			'img'			: $(productRow).getElement('.thumb').getElement('img').getProperty('src'),
			'url'			: $(priceTagElement).getElement('.tomer').getProperty('href'),
			'mid'			: parseInt($(priceTagElement).getProperty('data-mid')),
			'cluster'		: {
				'url'	: window.location.pathname,
				'title'	: ($('item-header').getElement('h1').innerText ? $('item-header').getElement('h1').innerText : $('item-header').getElement('h1').textContent)
			},
			'merchant'		: {
				'costs' : (parseInt(Math.random() * 2) == 1 ? 0 : 3000),
				'gift'	: ($(priceTagElement).getProperty('data-mgift') ? parseInt($(priceTagElement).getProperty('data-mgift')) : false),
				'logo' 	: $(priceTagElement).getProperty('data-mlogo'),
				'url'	: $(priceTagElement).getProperty('data-murl'),
				'title'	: $(priceTagElement).getProperty('data-mtitle')
			}
		};

		productRow.setProperty('data-hascart', 'true'); //used for ItemFilter object

		$(priceTagElement).cartElement = $C('a')
									.setClass('cart-icon' + (exists ? ' added' : ''))
									.setProperties({ 'href' : 'javascript:void(0);', 'title' : (exists ? 'Αφαίρεση από το καλάθι αγορών' : 'Προσθήκη στο καλάθι αγορών') })
									.setHTML((exists ? '-' : '+'))
									.injectIn($(priceTagElement))
									.addEvent('click', function() { 
										CartMachine.toggleCart(id, this, productStruct);
									});
	},

	toggleCart : function(id, cartIcon, productStruct) {
		
		var redirect = false;

		this.loadCart();

		if(typeof this.cartStruct.products[id] != "undefined") {

			// It's in the cart; remove it
			cartIcon && $(cartIcon).setProperty('title', 'Προσθήκη στο καλάθι αγορών').removeClass('added').setHTML('+');

			// Delete it
			delete this.cartStruct.products[id];

		} else {

			// It's not in the cart; add it
			cartIcon && $(cartIcon).setProperty('title', 'Αφαίρεση από το καλάθι αγορών').addClass('added').setHTML('-');	

			this.cartStruct.products[id] = productStruct;

			redirect = true;
		}

		this.flash = true;

		this.saveCart();

		if(redirect)
			window.location.href = '/cart#' + id;
	},

	saveCart : function(dontRedraw) {
		
		var jsonList = JSON.stringify(this.cartStruct);

		if(!window.safari && typeof localStorage != 'undefined')
			localStorage['cart'] = jsonList;
		else
			Cookie.set('cart', jsonList);

		if(dontRedraw)
			return;
				
		this.scanAndAttach();

		this.updateCartIcon();
		this.renderCart();

		if(this.flash) {
			
			this.flash = false;

			if(this.fixedHeader) {
					
				new Fx.Style(this.fixedHeader, 'opacity', { 

					'duration' 		: 200, 
					'onComplete' 	: function() {
					
						if(!CartMachine.fixedHeader)
							return;

						new Fx.Style(CartMachine.fixedHeader, 'opacity', { 

							'duration' 		: 200 
						}).start(0, 1);
							
					} 
				}).start(1, 0);
			}

			if($('noship-cartprice')) {
				
				new Fx.Style($('noship-cartprice'), 'opacity', { 

					'duration' 		: 200, 
					'onComplete' 	: function() {
					
						if(!$('noship-cartprice'))
							return;

						new Fx.Style($('noship-cartprice'), 'opacity', { 

							'duration' 		: 200 
						}).start(0, 1);
							
					} 
				}).start(1, 0);				
			}
		}
	},

	updateCartIcon : function() {

		this.fixedHeader && this.fixedHeader.remove();

		this.fixedHeader = $C('a', { 'id' : 'cart-header', 'href' : '/cart', 'title' : 'Καλάθι αγορών' }).injectBefore($('login-container').getElement('.anim')).setHTML(this.enumCart());
	},

	readHashAndRender : function() {
				
		if(!$('cart-container'))
			return;

		if(window.location.hash != '') {
		
			var id = parseInt(window.location.hash.split(/#/)[(window.ie && !window.ie9 ? 0 : 1)]);
			
			window.location.hash = '';

			if(typeof this.cartStruct.products[id] == "undefined") {

				this.renderCart();
				return;
			}

			var totalPrice = 0;

			for(i in this.cartStruct.products) {

				var product 	= this.cartStruct.products[i];
				var basePrice 	= product.priceNum;
				var finalPrice 	= (basePrice * product.q);
		
				totalPrice += finalPrice;
			}

			this.cartNotice && this.cartNotice.remove();
			this.cartNotice = $C('div', { 'id' : 'cart-notice' }).injectIn($('cart-container'));

			var product = this.cartStruct.products[id];
			var html 	= '';

			html += '<div class=\"addtocart-container clr\">';
			html += '<div class=\"left\">';
			html += '<h2>Πρόσθεσες 1 προϊόν στο καλάθι αγορών σου</h2>'
			html += '<table width="100%" class="cart-table no-border">';
			html += '<tbody>';
			html += '<tr>';
			html += '<td class="img"><a target="_blank" href="' + product.url + '"><img width="60" height="60" src="' + product.img + '"/></a></td>';
			html += '<th class="descr">';
			html += '<h3><a target="_blank" href="' + product.url + '">' + product.title + '</a></h3>';
			html += '<p><a href="' + product.merchant.url + '">' + product.merchant.title + '</a> <a class="sbutton" href="' + product.cluster.url + '">Σελίδα προϊόντος &rarr;</a></p>';

			if(product.merchant.gift !== false) {

				html += '<p>';
				html += '<span class=\"gift-select\">';
				html += '<input type=\"checkbox\" ' + (product.isGift ? 'checked=\"checked\"' : '') + ' onchange=\"CartMachine.toggleProductHasGift(' + id + ', this, true);\" id=\"' + id +'-gift\"/>';
				html += '<label for=\"' + id + '-gift\">Αυτό το προϊόν θα είναι δώρο</label>';
				html += '</span>';
				html += '</p>';
			}

			html += '</th>';
			html += '<td class="price"><span>' + (product.priceNum / 100).format('0,0.00') + '</span></td>';
			html += '</tr>';
			html += '</tbody>';
			html += '</table>';
			html += '</div>';

			html += '<div class="right">';
			html += '<div class="foot">';
			html += '<p><strong>' + this.enumCart() + '</strong> ' + (this.enumCart() == 1 ? 'προϊόν' : 'προϊόντα') + ' στο καλάθι αγορών.</p>';
			html += '<p>Σύνολική αξία χωρίς μεταφορικά: <strong>' + (totalPrice / 100).format('0,0.00') + '</strong></p>';
			html += '<a class="button" href="javascript:void(0);" onclick="CartMachine.renderCart();">Μετάβαση στο καλάθι αγορών</a> ';
			html += '<input type="button" class="button" onclick="CartMachine.completeOrder();" value="' + (typeof window.User.ak == 'undefined' ? 'Συνδέση για ολοκλήρωση αγοράς &raquo;' : 'Ολοκλήρωση αγοράς &raquo;') + '"/>';
			html += '</div>';
			html += '</div>';

			html += '</div>';

			this.cartNotice.setHTML(html);

		} else
			this.renderCart();
	},

	completeOrder : function() {
		
		if(typeof window.User.ak == 'undefined') {
			
			LoginRegisterBox.registerRender(undefined, true);
			return;
		}

		this.cartTable && this.cartTable.remove();
		this.cartTable = null;

		var html = '';

		html += this.renderTimeline('address');
		html +='<h2>Συμπλήρωσε την διεύθυνσή σου.</h2>';
		html += '<form method="post" action="" id="shipping-info" class="cart-form">';
		html +='<table>';
		html +='<tbody>';
		html +='<tr>';
		html +='<td>';
		html +='<label for="enterAddressFullName">Ονοματεπώνυμο:</label>';
		html +='</td>';
		html +='<td>';
		html +='<input autofocus type="text" name="enterAddressFullName" id="enterAddressFullName" class="field" size="50" maxlength="50" value="' + (typeof this.cartStruct.user.fullname != 'undefined' ? this.cartStruct.user.fullname : '') + '"/>';
		html +='</td>';
		html +='</tr>';
		html +='<tr>';
		html +='<td>';
		html +='<label for="enterAddressAddressLine1">Διεύθυνση:</label>';
		html +='</td>';
		html +='<td>';
		html +='<input value="' + (typeof this.cartStruct.user.address != 'undefined' ? this.cartStruct.user.address : '') + '" placeholder="Αριθμός και οδός κατοικίας ή χώρου εργασίας" type="text" name="enterAddressAddressLine1" id="enterAddressAddressLine1" class="field" size="50" maxlength="60">';
		html +='</td>';
		html +='</tr>';
		html +='<tr>';
		html +='<td>';
		html +='<label for="enterAddressCity">Πόλη:</label>';
		html +='</td>';
		html +='<td>';
		html +='<input value="' + (typeof this.cartStruct.user.city != 'undefined' ? this.cartStruct.user.city : '') + '" type="text" name="enterAddressCity" id="enterAddressCity" class="field" size="25" maxlength="50">';
		html +='</td>';
		html +='</tr>';
		html +='<tr>';
		html +='<td>';
		html +='<label for="enterAddressPostalCode">Ταχ. Κώδικας:</label>';
		html +='</td>';
		html +='<td>';
		html +='<input value="' + (typeof this.cartStruct.user.postal != 'undefined' ? this.cartStruct.user.postal : '') + '" type="text" name="enterAddressPostalCode" id="enterAddressPostalCode" class="field" size="20" maxlength="20">';
		html +='</td>';
		html +='</tr>';
		html +='<tr>';
		html +='<td>';
		html +='<label for="enterAddressCountryCode">Χώρα:</label>';
		html +='</td>';
		html +='<td>';
		html +='<select name="enterAddressCountryCode" class="field" id="enterAddressCountryCode">';
		html +='<option value="">--</option>';

		for(country in this.countries)
			html +='<option ' + (typeof this.cartStruct.user.country != 'undefined' && this.cartStruct.user.country == country ? 'selected="selected"' : (typeof this.cartStruct.user.country == 'undefined' && country == 'GR' ? 'selected="selected"' : '')) + ' value="' + country + '">' + this.countries[country] + '</option>';

		html +='</select>';
		html +='</td>';
		html +='</tr>';
		html +='<tr>';
		html +='<td>';
		html +='<label for="enterAddressPhoneNumber">Τηλέφωνο:</label>';
		html +='</td>';
		html +='<td>';
		html +='<input value="' + (typeof this.cartStruct.user.phone != 'undefined' ? this.cartStruct.user.phone : '') + '" type="text" name="enterAddressPhoneNumber" id="enterAddressPhoneNumber" class="field" size="15" maxlength="20">';
		html +='</td>';
		html +='</tr>';
		html+='<tr><td></td><td class="pale">Όλα τα πεδία είναι υποχρεωτικά</td></tr>';
		html +='</tbody>';
		html +='</table>';
		html += '</form>';
		
		html += '<p class="foot clr"><input type="button" class="left button" onclick="CartMachine.renderCart();" value="&laquo; Καλάθι αγορών"/><input type="button" class="right button" onclick="CartMachine.saveUserInfo();" value="Υπολογισμός εξόδων αποστολής &raquo;"/></p>';

		html += this.renderFooter();

		$('cart-container').setHTML(html);

		(function() { $('cart-container').addClass('animated'); }).delay(10);
		
		$('shipping-info') && this.enableEnterOnForm($('shipping-info'), function() { CartMachine.saveUserInfo(); });
	},

	renderFooter : function() {
		
		var html = '';

		html += '<div class="faq">';
		html += '<h4 class="clr">';
		html += 'Συχνές ερωτήσεις';
		html += '<span class="secure">Ασφαλής συναλλαγή</span>';
		html += '</h4>';
		html += '<ul>';
		html += '<li>';
		html += '<details>';
		html += '<summary>Πως υπολογίζονται τα έξοδα αποστολής;</summary>';
		html += '<p>Pellentesque pharetra accumsan libero, id laoreet felis iaculis in. Integer rhoncus malesuada sollicitudin. Phasellus magna mi, vulputate vitae varius eget, suscipit</p>';
		html += '</details>';
		html += '</li>';
		html += '<li>';
		html += '<details>';
		html += '<summary>Πως λειτουργεί το BestPrice One&trade;;</summary>';
		html += '<p>Quisque eget dui quam. Suspendisse potenti. Maecenas mollis volutpat posuere. Integer feugiat placerat tellus, in imperdiet</p>';
		html += '<p>dignissim magna. Curabitur eget cursus massa. Suspendisse potenti. Nam tempor, sapien ut tincidunt pulvinar, velit nulla hen</p>';
		html += '<p>ui. Cras libero neque, placerat vitae dapibus at, sollicitudin ac massa. Curabitur vulputate accumsan nisi vitae mollis. Sed ri</p>';
		html += '</details>';
		html += '</li>';
		html += '</ul>';
		html += '</div>';

		return html;
	},

	saveUserInfo : function() {
		
		if(typeof window.User.ak == 'undefined') {
			
			LoginRegisterBox.registerRender(undefined, true);
			return;
		}

		var form 		= $('shipping-info');
		var empty 		= false;

		$(form).getElements('input,select').each(function() {
			
			if(empty)
				return;

			if($(this).getValue() == '') {
				
				alert('Όλα τα πεδία είναι υποχρεωτικά');
				$(this).focus();

				empty = true;
			}
		});

		if(empty)
			return;

		this.cartStruct.user.fullname 	= $('enterAddressFullName').getValue();
		this.cartStruct.user.address 	= $('enterAddressAddressLine1').getValue();	
		this.cartStruct.user.city 		= $('enterAddressCity').getValue();
		this.cartStruct.user.postal 	= $('enterAddressPostalCode').getValue();
		this.cartStruct.user.country 	= $('enterAddressCountryCode').getValue();
		this.cartStruct.user.phone 		= $('enterAddressPhoneNumber').getValue();

		this.saveCart(true);

		this.renderShippingCosts();
	},

	renderShippingCosts : function() {

		var merchants 	= {};
		var html 		= '';
		var totalPrice 	= 0

		for(pid in this.cartStruct.products) {
			
			var product = this.cartStruct.products[pid];
			var basePrice 	= product.priceNum;
			var finalPrice 	= (basePrice * product.q);

			merchants[product.mid] = product.merchant;

			totalPrice += finalPrice;
		}

		html += this.renderTimeline('shipping');		
		html +='<h2>Υπολογισμός εξόδων αποστολής.</h2>';
		html += '<table class="shipping-costs">';
		html += '<thead>';
		html += '<tr><th>Κατάστημα</th><td>Έξοδα αποστολής</td></tr>';
		html += '</thead>';
		html += '<tbody>';

		var shippingCosts = 0;

		for(mid in merchants) {
			
			var merchant = merchants[mid];

			html += '<tr>';
			html += '<th><a href="' + merchant.url + '" title="Σελίδα καταστήματος"><img src="' + merchant.logo + '" width="90" height="30" />' + merchant.title + '</a></th>';
			html += '<td>' + (merchant.costs == 0 ? 'Δωρεάν' : (merchant.costs / 100).format('0,0.00')) + '</td>';
			html += '</tr>';	

			shippingCosts += merchant.costs;
		}

		html += '<tbody>';
		html += '<tfoot>';
		html += '<th colspan="2">Συνολικά έξοδα αποστολής: <strong>' + (shippingCosts / 100).format('0,0.00') + '</strong></th>';
		html += '</tfoot>';
		html += '</table>';

		var finalPrice = totalPrice + shippingCosts;

		html += '<table class="final-price">';
		html += '<tbody>';
		html += '<tr>';
		html += '<td><span class="price">' + (totalPrice / 100).format('0,0.00') + '</span><span>Αξία προϊόντων</span></td>';
		html += '<td class="sign">+</td>';
		html += '<td><span class="price">' + (shippingCosts / 100).format('0,0.00') + '</span><span>Έξοδα αποστολής</span></td>';
		html += '<td class="sign">=</td>';
		html += '<th class="final"><span class="price">' + (finalPrice / 100).format('0,0.00') + '</span><span>Τελική τιμή με Φ.Π.Α.</span></th>';
		html += '</tr>';
		html += '</tbody>';
		html += '</table>';

		html += '<p class="foot clr"><input type="button" class="left button" onclick="CartMachine.completeOrder();" value="&laquo; Ορισμός διεύθυνσης αποστολής"/><input type="button" class="right button" onclick="CartMachine.pay();" value="Επιλογή τρόπου πληρωμής &raquo;"/></p>';

		html += this.renderFooter();

		$('cart-container').setHTML(html);
		(function() { $('cart-container').addClass('animated'); }).delay(10);
	},

	pay : function() {
			
		if(typeof window.User.ak == 'undefined') {
			
			LoginRegisterBox.registerRender(undefined, true);
			return;
		}
		
		var html 			= '';

		html += this.renderTimeline('pay');
		html +='<h2>Πώς θα ήθελες να πληρώσεις;</h2>';

		html += '<table id="cart-payment-methods" class="payment-methods">';
		html += '<tbody>';
		html += '<tr>';
		html += '<td class="ccard' + ((typeof this.cartStruct.user.payment != 'undefined' && this.cartStruct.user.payment == 'cc') || typeof this.cartStruct.user.payment == 'undefined' ? ' selected' : '') + '" onclick="CartMachine.selectPaymentMethod(\'ccard\');"><label for="ccard">Πιστωτική κάρτα</label><input onchange="CartMachine.selectPaymentMethod(\'ccard\');" value="ccard" id="ccard" ' + ((typeof this.cartStruct.user.payment != 'undefined' && this.cartStruct.user.payment == 'cc') || typeof this.cartStruct.user.payment == 'undefined' ? 'checked="checked"' : '') + ' type="radio" name="pmethod"/></span></td>';
		html += '<td class="paypal' + (typeof this.cartStruct.user.payment != 'undefined' && this.cartStruct.user.payment == 'paypal' ? ' selected' : '') + '" onclick="CartMachine.selectPaymentMethod(\'paypal\');"><label for="paypal">Paypal</label><input onchange="CartMachine.selectPaymentMethod(\'paypal\');" value="paypal" id="paypal" type="radio" name="pmethod" ' + (typeof this.cartStruct.user.payment != 'undefined' && this.cartStruct.user.payment == 'paypal' ? 'checked="checked"' : '') + '/></span></td>';
		html += '<td class="cod' + (typeof this.cartStruct.user.payment != 'undefined' && this.cartStruct.user.payment == 'cod' ? ' selected' : '') + '" onclick="CartMachine.selectPaymentMethod(\'cod\');"><label for="cod">Αντικαταβολή</label><input onchange="CartMachine.selectPaymentMethod(\'cod\');" value="cod" id="cod" type="radio" name="pmethod" ' + (typeof this.cartStruct.user.payment != 'undefined' && this.cartStruct.user.payment == 'cod' ? 'checked="checked"' : '') + '/></span></td>';
		html += '</tr>';
		html += '</tbody>';
		html += '</table>';

		html += '<ul id="payment-options">';

		html += '<li id="ccard-box" ' + ((typeof this.cartStruct.user.payment != 'undefined' && this.cartStruct.user.payment == 'cc') || typeof this.cartStruct.user.payment == 'undefined' ? '' : 'style="display:none;"') + '>';

		html += '<form method="post" action="" id="pay-cc" class="cart-form">';
		html +='<table>';
		html +='<thead><tr><td></td><td class="supported-cards clr"><span title="Visa" class="visa"></span><span title="Visa Electron" class="visaelectron"></span><span title="Mastercard" class="mastercard"></span><span title="American Express" class="americanexpress"></span><span title="Cirrus" class="cirrus"></span></td></tr></thead>';
		html +='<tbody>';
		html +='<tr>';
		html +='<td>';
		html +='<label for="cc_number">Αριθμός κάρτας:</label>';
		html +='</td>';
		html +='<td>';

		if(typeof this.cartStruct.user.cc_number != 'undefined')
			html += '<span>Πιστωτική που λήγει σε <strong>' + (this.cartStruct.user.cc_number%10000) + '</strong> <a href="javascript:void(0);" onclick="$(this).getParent().hide();$(\'cc_number\').show();">(αλλαγή)</a></span>';

		html +='<input ' + (typeof this.cartStruct.user.cc_number != 'undefined' ? 'style="display: none;" value="' + this.cartStruct.user.cc_number + '"' : '') + ' placeholder="Ο αριθμός της κάρτας χωρίς κενά ή παύλες" type="text" name="cc_number" id="cc_number" class="field" size="50" maxlength="50"/>';
		html +='</td>';
		html +='</tr>';
		html +='<tr>';
		html +='<td>';
		html +='<label for="cc_name">Όνομα στην κάρτα:</label>';
		html +='</td>';
		html +='<td>';
		html +='<input ' + (typeof this.cartStruct.user.cc_name != 'undefined' ? 'value="' + this.cartStruct.user.cc_name + '"' : '') + ' placeholder="Όπως ακριβώς αναγράφεται στην κάρτα" type="text" name="cc_name" id="cc_name" class="field" size="50" maxlength="60">';
		html +='</td>';
		html +='</tr>';
		html +='<tr>';
		html +='<td>';
		html +='<label for="cc_exp_month">Ημερομηνία λήξης</label>';
		html +='</td>';
		html +='<td>';
		
		html +='<select name="cc_exp_month" id="cc_exp_month" class="field">';

		for(var i = 1; i < 13; i++) {
			
			html += '<option ' + (typeof this.cartStruct.user.cc_exp_month != 'undefined' && this.cartStruct.user.cc_exp_month == i ? 'selected="selected"' : '') + ' value="' + i + '">' + (i + '').pad() + ' - ' + (new Date()).set('1/' + i + '/2012').format('F') + '</option>';
		}

		html += '</select>&nbsp;&nbsp;';

		html +='<select name="cc_exp_year" id="cc_exp_year" class="field">';

		for(var i = parseInt((new Date).format('Y')); i < parseInt((new Date).format('Y')) + 20; i++) {
			
			html += '<option ' + (typeof this.cartStruct.user.cc_exp_year != 'undefined' && this.cartStruct.user.cc_exp_year == i ? 'selected="selected"' : '') + ' value="' + i + '">' + i + '</option>';
		}
		
		html += '</select>';

		html +='</td>';
		html +='</tr>';
		html += '</tbody>';
		html += '</table>';
		html += '</li>';

		html += '<li id="paypal-box" ' + (typeof this.cartStruct.user.payment != 'undefined' && this.cartStruct.user.payment == 'paypal' ? '' : 'style="display:none;"') + '>';
		html += '<a href="javascript:void(0);" onclick="alert(\':)\');" class="button paypal-button">Μετάβαση στο PayPal &rarr;</a>';
		html += '</li>';

		html += '<li id="cod-box"  ' + (typeof this.cartStruct.user.payment != 'undefined' && this.cartStruct.user.payment == 'cod' ? '' : 'style="display:none;"') + '>';
		html += '<p class="pale">Προσωρινά ανενεργός τρόπος πληρωμής</p>';
		html += '</li>';

		html += '</ul>';

		html += '<p class="foot clr"><input type="button" class="left button" onclick="CartMachine.renderShippingCosts();" value="&laquo; Υπολογισμός εξόδων αποστολής"/><input type="button" class="right button" onclick="CartMachine.savePayment();" value="Επιβεβαίωση & πληρωμή &raquo;"/></p>';

		html += this.renderFooter();

		$('cart-container').setHTML(html);
		(function() { $('cart-container').addClass('animated'); }).delay(10);

		$('pay-cc') && this.enableEnterOnForm($('pay-cc'), function() { CartMachine.savePayment(); });
	},

	enableEnterOnForm : function(formElement, callbackFunction) {
		
		$(formElement).getElements('input[type="text"]').addEvent('keydown', function(event) {
			
			if(event.code != 13)
				return false;

			callbackFunction();
		});
	},

	savePayment : function() {

		if(typeof window.User.ak == 'undefined') {
			
			LoginRegisterBox.registerRender(undefined, true);
			return;
		}

		if($('ccard').checked) {
			
			var form 		= $('pay-cc');
			var empty 		= false;

			$(form).getElements('input,select').each(function() {
				
				if(empty)
					return;

				if($(this).getValue() == '') {
					
					alert('Όλα τα πεδία είναι υποχρεωτικά');
					$(this).focus();

					empty = true;

				} else if($(this).id == 'cc_number' && parseInt($(this).getValue()) < 1000000000000000) {
					
					alert('Πληκτρολόγησε σωστό αριθμό πιστωτικής κάρτας');
					$(this).focus();

					empty = true;
				}
			});

			if(empty)
				return;

			this.cartStruct.user.cc_number 		= $('cc_number').getValue();
			this.cartStruct.user.cc_name	 	= $('cc_name').getValue();
			this.cartStruct.user.cc_exp_month 	= $('cc_exp_month').getValue();
			this.cartStruct.user.cc_exp_year 	= $('cc_exp_year').getValue();
			this.cartStruct.user.payment 		= 'cc'
			
		} else if($('paypal').checked)
			this.cartStruct.user.payment = 'paypal';
		else
			this.cartStruct.user.payment = 'cod';

		this.saveCart(true);

		this.renderDone();
	},

	renderDone : function() {
	
		if(typeof window.User.ak == 'undefined') {
			
			LoginRegisterBox.registerRender(undefined, true);
			return;
		}
		
		var html 			= '';

		html += this.renderTimeline('done');
		html +='<h2>Επιβεβαίωσε την παραγγελία σου.</h2>';

		var merchants 		= {};
		var shippingCosts 	= 0;
		var totalPrice 		= 0

		for(pid in this.cartStruct.products) {
			
			var product = this.cartStruct.products[pid];
			var struct  = {
				'product' : product,
				'merchant': product.merchant
			};

			merchants[product.mid] 					= merchants[product.mid] || {};
			merchants[product.mid].info 			= product.merchant;
			merchants[product.mid].products 		= merchants[product.mid].products || {};
			merchants[product.mid].products[pid] 	= product;
		}

		html += '<table width="100%" class="order-summary cart-table">';
		html += '<thead>';
		html += '<tr>';
		html += '<th class="sep">Διεύθυνση αποστολής <a href="javascript:void(0);" onclick="CartMachine.completeOrder();">(αλλαγή)</a></th>'
		html += '<th>Τρόπος πληρωμής <a href="javascript:void(0);" onclick="CartMachine.pay();">(αλλαγή)</a></th>'
		html += '</tr>';
		html += '</thead>';
		html += '<tbody>';
		html += '<tr>';
		html += '<td class="sep">';
		html += '<p>' + this.cartStruct.user.fullname + '</p>';
		html += '<p>' + this.cartStruct.user.address + '</p>';
		html += '<p>' + this.cartStruct.user.city + ', ' + this.cartStruct.user.postal + '</p>';
		html += '<p>' + this.countries[this.cartStruct.user.country] + '</p>';
		html += '<p>Τηλέφωνο: ' + this.cartStruct.user.phone + '</p>';
		html += '</td>';
		html += '<td>'

		if(this.cartStruct.user.payment == "cc")
			html += '<p class="cc">Κάρτα που λήγει σε <strong>' + (this.cartStruct.user.cc_number%10000) + '</strong></p>';
		else if(this.cartStruct.user.payment == "paypal")
			html += '<p class="paypal">Πληρωμή μέσω Paypal</p>';
		else
			html += '<p>Πληρωμή με αντικαταβολή</p>';

		html += '</td>';
		html += '</tr>';
		html += '</tbody>';
		html += '</table>';

		html += '<div class="grouped-container">';
		html += '<table width="100%" class="grouped-merchants cart-table">';

		for(mid in merchants) {
			
			var merchant = merchants[mid];

			html += '<thead><tr><th colspan="4">Προϊόντα που θα αποσταλλούν από ' + merchant.info.title + '</th></tr></thead>';
			html += '<tbody>';

			for(pid in merchant.products) {
				
				var product 	= merchant.products[pid];
				var basePrice 	= product.priceNum;
				var finalPrice 	= (basePrice * product.q);

				html += '<tr>';
				html += '<td class="img"><a target="_blank" href="' + product.url + '"><img width="60" height="60" src="' + product.img + '"/></a></td>';
				html += '<th class="descr">';
				html += '<h3>';
				html += '<a target="_blank" href="' + product.url + '">' + product.title + '</a>';

				if(product.isGift)
					html += '<span class=\"is-gift\">δώρο</span>';

				html += '</h3>';
				html += '</th>';
				html += '<td class="fprice">Ποσότητα: <strong>' + product.q + '</strong> <a href="javascript:void(0);" onclick="CartMachine.renderCart();">(αλλαγή)</a></td>';
				html += '<td class="price">' + (product.priceNum / 100).format('0,0.00') + '</td>';
				html += '</tr>';	
					
				totalPrice += finalPrice;
			}

			html += '</tbody>';

			shippingCosts += merchant.info.costs;
		}
		
		html += '<tfoot>';
		html += '<tr>';
		html += '<td colspan="2" class="empty"></td>';
		html += '<td class="label empty">Αξία προϊόντων</td>';
		html += '<td class="price empty">' + (totalPrice / 100).format('0,0.00') + '</td>';
		html += '</tr>';
		html += '<tr>';
		html += '<td colspan="2" class="empty"></td>';
		html += '<td class="label empty">Έξοδα αποστολής</td>';
		html += '<td class="price empty">+ ' + (shippingCosts / 100).format('0,0.00') + '</td>';
		html += '</tr>';
		html += '<tr>';
		html += '<td colspan="2" class="empty"></td>';
		html += '<td class="label empty"><strong>Τελική τιμή με Φ.Π.Α.</strong></td>';
		html += '<td class="price empty"><span>' + ((shippingCosts + totalPrice) / 100).format('0,0.00') + '</span></td>';
		html += '</tr>';
		html += '</tfoot>';

		html += '</table>';
		html += '</div>';

		html += '<div class="pay-container">';
		html += '<a href="javascript:void(0);" id="purchase-products" class="button" onclick="CartMachine.buyNow();">Εκτέλεση αγοράς</a>';
		html += '</div>';

		html += this.renderFooter();

		$('cart-container').setHTML(html);
		(function() { $('cart-container').addClass('animated'); }).delay(10);	
	},

	buyNow : function() {
		
		alert(':)');
	},

	selectPaymentMethod : function(method) {
		
		$('cart-payment-methods').getElements('tbody td').each(function() {

			this.getElement('input').setProperty('checked', '');
			this.removeClass('selected');
		});

		$('cart-payment-methods').getElement('td.' + method).addClass('selected');
		$('cart-payment-methods').getElement('td.' + method + ' input').setProperty('checked', 'checked');

		$('payment-options').getElements('li').each(function() { this.hide(); });
		$(method + '-box').show();
	},

	renderTimeline : function(active) {
		
		var cartLink 		= (active == 'address' || active == 'shipping' || active == 'pay' || active == 'done');
		var addressLink 	= (active == 'shipping' || active == 'pay' || active == 'done');
		var shippingLink 	= (active == 'pay' || active == 'done');
		var paymentLink	 	= (active == 'done');

		var html = '';
	
		html += '<ul class="timeline">';
		html += '<li class="' + (active == 'cart' ? 'active ' : '') + 'cart">';
		html += '<span class="dot' + (cartLink ? ' link' : '') + '"' + (cartLink ? ' onclick="CartMachine.renderCart();"' : '') + '><em>&nbsp;</em></span>';
		html += '<span class="label">';
		html += (cartLink ? '<a href="javascript:void(0);" onclick="CartMachine.renderCart();">' : '');
		html += 'Καλάθι';
		html += (cartLink ? '</a>' : '');
		html += '</span>';
		html += '</li>';
		html += '<li class="' + (active == 'address' ? 'active ' : '') + 'address">';
		html += '<span class="dot' + (addressLink ? ' link' : '') + '"' + (addressLink ? ' onclick="CartMachine.completeOrder();"' : '') + '><em>&nbsp;</em></span>';
		html += '<span class="label">';
		html += (addressLink ? '<a href="javascript:void(0);" onclick="CartMachine.completeOrder();">' : '');
		html += 'Διεύθυνση';
		html += (addressLink ? '</a>' : '');
		html += '</span>';
		html += '</li>';
		html += '<li class="' + (active == 'shipping' ? 'active ' : '') + 'shipping">';
		html += '<span class="dot' + (shippingLink ? ' link' : '') + '"' + (shippingLink ? ' onclick="CartMachine.renderShippingCosts();"' : '') + '><em>&nbsp;</em></span>';
		html += '<span class="label">';
		html += (shippingLink ? '<a href="javascript:void(0);" onclick="CartMachine.renderShippingCosts();">' : '');
		html += 'Έξοδα αποστολής';
		html += (shippingLink ? '</a>' : '');
		html += '</span>';
		html += '</li>';
		html += '<li class="' + (active == 'pay' ? 'active ' : '') + 'pay">';
		html += '<span class="dot' + (paymentLink ? ' link' : '') + '"' + (paymentLink ? ' onclick="CartMachine.pay();"' : '') + '><em>&nbsp;</em></span>';
		html += '<span class="label">';
		html += (paymentLink ? '<a href="javascript:void(0);" onclick="CartMachine.pay();">' : '');
		html += 'Τρόποι πληρωμής';
		html += (paymentLink ? '</a>' : '');
		html += '</span>';
		html += '</li>';
		html += '<li class="' + (active == 'done' ? 'active ' : '') + 'done">';
		html += '<span class="dot"><em>&nbsp;</em></span>';
		html += '<span class="label">';
		html += 'Τέλος!';
		html += '</span>';
		html += '</li>';
		html += '</ul>';

		return html;
	},

	renderCart : function() {
		
		if(!$('cart-container'))
			return;

		$('cart-container').setHTML('');
		this.cartTable = null;
		this.cartNotice = null;
		
		this.cartTable = $C('div', { 'id' : 'cart' }).injectIn($('cart-container'));

		var html 		= '';
		var totalPrice 	= 0;

		if(this.enumCart() > 0) {

			html += this.renderTimeline('cart');

			html +='<h2>Έχεις ' + (this.enumCart() == 1 ? '1 προϊόν' : this.enumCart() + ' προϊόντα') + ' στο καλάθι αγορών σου.</h2>';

			html +='<table width="100%" class="cart-table">';
			html +='<thead>';
			html +='<tr>';
			html +='<th colspan="2">Προϊόν</th>';
			html +='<td class="price-head">Τιμή</td>';
			html +='<td class="quantity-head">Ποσότητα</td><td></td>';
			html +='</tr>';
			html +='</thead>';
			html +='<tbody>';
	
			for(id in this.cartStruct.products) {

				var product 	= this.cartStruct.products[id];
				var basePrice 	= product.priceNum;
				var finalPrice 	= (basePrice * product.q);

				html += '<tr>';
				html += '<td class="img"><a target="_blank" href="' + product.url + '"><img width="60" height="60" src="' + product.img + '"/></a></td>';
				html += '<th class="descr">';
				html += '<h3><a target="_blank" href="' + product.url + '">' + product.title + '</a></h3>';
				html += '<p>';
				html += '<a href="' + product.merchant.url + '">' + product.merchant.title + '</a> <a class="sbutton" href="' + product.cluster.url + '">Σελίδα προϊόντος &raquo;</a>';
				html += '</p>';
				
				if(product.merchant.gift !== false) {

					html += '<p>';
					html += '<span class=\"gift-select\">';
					html += '<input type=\"checkbox\" ' + (product.isGift ? 'checked=\"checked\"' : '') + ' onchange=\"CartMachine.toggleProductHasGift(' + id + ', this);\" id=\"' + id +'-gift\"/>';
					html += '<label for=\"' + id + '-gift\">Αυτό το προϊόν θα είναι δώρο</label>';
					html += '</span>';
					html += '</p>';
				}

				html += '</th>';
				html += '<td class="price"><span>' + (product.priceNum / 100).format('0,0.00') + '</span></td>';
				html += '<td class="fprice"><input data-prev="' + product.q + '" type="text" class="field" value="' + product.q + '" onchange="CartMachine.refreshQuantities(' + id + ', this);"/></td>'; //=' + finalPrice + '&euro;
				html += '<td class="remove"><a href="javascript:void(0);" title="Αφαίρεση από το καλάθι αγορών" onclick="if(confirm(\'Είσαι σίγουρος ότι θέλεις να αφαιρέσεις το προϊόν από το καλάθι αγορών σου;\')) { CartMachine.toggleCart(' + id + '); }">Αφαίρεση</a></td>';
				html += '</tr>';

				totalPrice += finalPrice;
			}

			html +='</tbody>';

			html += '<tfoot>';
			html += '<tr>';
			html += '<th colspan="5">Σύνολο (χωρίς μεταφορικά) <span id=\"noship-cartprice\">' + (totalPrice / 100).format('0,0.00') + '</span></th>';
			html += '</tr>';
			html += '</tfoot>';
			
			html +='</table>';

			html += '<p class="foot"><input type="button" class="button" onclick="CartMachine.completeOrder();" value="' + (typeof window.User.ak == 'undefined' ? 'Συνδέση για ολοκλήρωση αγοράς &raquo;' : 'Ορισμός διεύθυνσης αποστολής &raquo;') + '"/></p>';

			html += this.renderFooter();

		} else
			html += '<div class="sorry-face"><strong>:(</strong><p>Δεν έχεις προσθέσει ακόμη προϊόντα στο καλάθι αγορών σου!</p></div>';

		this.cartTable.setHTML(html);

		(function() { $('cart-container').addClass('animated'); }).delay(10);
	},

	toggleProductHasGift : function(id, element, switchToCart) {
		
		if(typeof this.cartStruct.products[id] == 'undefined' || this.cartStruct.products[id].merchant.gift === false)
			return;

		if(element.checked == false && this.cartStruct.products[id].oldBasePrice)
			this.cartStruct.products[id].priceNum = this.cartStruct.products[id].oldBasePrice;
		else {
			this.cartStruct.products[id].oldBasePrice = this.cartStruct.products[id].priceNum;
			this.cartStruct.products[id].priceNum = this.cartStruct.products[id].priceNum + this.cartStruct.products[id].merchant.gift;
		}

		this.cartStruct.products[id].isGift = element.checked;

		this.flash = true;
		this.saveCart(switchToCart);
	},

	refreshQuantities : function(id, element) {
		
		if(!element)
			return;

		if(typeof this.cartStruct.products[id] == "undefined")
			return;

		var q = parseInt($(element).getValue());

		if(isNaN(q) || q < 0)
			q = parseInt($(element).getProperty('data-prev'));

		if(q == 0) {
			
			this.toggleCart(id);
			return;
		}

		this.cartStruct.products[id].q = q;

		this.flash = true;
		this.saveCart();
	}
}

CompareMachine = {
	
	'eligibleCats'	: [2591,3446,2621,2562,2560,2559,2557,2569,2570,2561,2583,2553,2588,2606,2608,2610,2609,2611,2613,3464,2617,2627,2628,2630,2633,3048,3003,3013,3022,697,3043,3439,5802,709,715,698,806,799,800,876,889,891,886,892,887,5501,888,2442,3236,3161,3163,3162,3164,2502,2508,2509,2510,2512,2516,5807,5809,5808,2485,2484,2486],
	'limit' 		: 4,

	initialize : function() {

		if($('page-iframe'))
			return;

		// Initialize struct		
		this.compareStruct = {
			'cid'		: 0,
			'products'	: {}
		};

		this.loadList();

		// If we are in search/category page, display the compare button in 
		// products that are in the same category with the comparable products
		this.scanAndAttach();
		
		// If we are in product page, display the compare button if 
		// product is in the same category with the comparable products
		this.attachToProduct();

		// Render the compare tables
		this.buildFixedCompareTable();
		this.buildHeaderCompareText();

		if($('page-compare')) {

			this.attachProductRemovalButtonsToCompareTable();

			this.featuresHeader 		= $('page-compare').getElement('.features-header');
			this.featuresHeaderParent	= this.featuresHeader.getParent();

			if(!window.hasEvent('scroll')) {
				
				window.addEvent('scroll', function(event) {

					if(CompareMachine.isAnimating)
						return;
					
					var scrollTop = window.getScrollTop();		

					if(scrollTop >= 276 && !CompareMachine.featuresHeaderParent.hasClass('fixed'))
						CompareMachine.featuresHeaderParent.addClass('fixed');
					else if(scrollTop < 276 && CompareMachine.featuresHeaderParent.hasClass('fixed'))
						CompareMachine.featuresHeaderParent.removeClass('fixed');
				});
			}	
		}
	},

	loadList : function() {
		
		// Read the compare list from localStorage or Cookie
		if(!window.safari && typeof localStorage != 'undefined' && typeof localStorage['compare'] != 'undefined' && localStorage['compare'] != null)
			this.compareStruct = JSON.parse(localStorage['compare']);
		else if(Cookie.get('compare') && Cookie.get('compare') != "")	
			this.compareStruct = JSON.parse(Cookie.get('compare'));
	},

	attachProductRemovalButtonsToCompareTable : function() {

		var products = $('page-compare').getElements('thead .img th');

		if(products.length == 0)
			return;

		// Check if the products in the lists are the products of the users list
		// if yes, then every change in this list will be reflected on his list
		// otherwise user will remove (and add) products without saving the state
		// only by changing the url

		var productsOfList 	= 0;

		this.productIds = {};

		products.each(function() {

			var pid = parseInt($(this).getProperty('data-pid'));
			var cid = parseInt($(this).getProperty('data-cid'));
		
			CompareMachine.listCid 			= cid;	
			CompareMachine.productIds[pid] 	= true;

			for(id in CompareMachine.compareStruct.products) {
				
				if(pid == id)
					productsOfList++;
			}
		});

		this.isUserList = (this.enumList() > 0 && productsOfList == this.enumList() ? true : false);

		products.each(function() {

			var element = this;
			var id 		= parseInt($(element).getProperty('data-pid'));

			if(id == 0 || isNaN(id))
				return;

			$C('a')
			.setProperty('title', 'Αφαίρεση από την λίστα σύγκρισης')
			.setProperty('href', 'javascript:void(0);')
			.setHTML('remove')
			.setClass('remove-list')
			.injectIn($(element).getElement('div'))
			.addEvent('click', function() { 				

				if(CompareMachine.isUserList) {

					CompareMachine.removeFromList(id);
					window.location = CompareMachine.buildCompareURI();

				} else {
					
					delete CompareMachine.productIds[id];
						
					var ids = [];

					for(id in CompareMachine.productIds)
						ids.push(id);

					window.location = '/compare/' + ids.join('/');
				}
			});
		});

		$('clear-list') && $('clear-list').addEvent('click', function() { 

				CompareMachine.clearList();

				window.location = ($('compare-category') ? $('compare-category').getProperty('href') : '/compare/'); 
		});

		this.attachAddHandlerToProductListing($('top-products'));

		if($('searchandadd')) { 

			$('searchandadd').getParent().addEvent('submit', function(event) { event.stop(); });
			$('searchandadd').addEvent('keyup', function(event) { 

				if(event.code == 27 && $(this).getValue() != "") {
					
					$(this).setValue('');
					CompareMachine.revertToPopular();
					return;
				}

				CompareMachine.autocomplete(this.getValue()); 
			});
		}
	},

	attachAddHandlerToProductListing : function(container) {
			
		$(container) && $(container).getElements('li').addEvent('click', function(event) {
			
			event.stop();

			var pid 	= parseInt($(this).getProperty('data-pid'));
			var cid 	= parseInt($(this).getProperty('data-cid'));
			var imgURL 	= $(this).getElement('img').getProperty('src');
			var prodURL = $(this).getElement('a').getProperty('href');
			var title 	= ($(this).getElement('p').innerText ? $(this).getElement('p').innerText : $(this).getElement('p').textContent);

			if(CompareMachine.isUserList) {

				CompareMachine.addToList(pid, cid, title, imgURL, prodURL);
				window.location = CompareMachine.buildCompareURI();

			} else {
			
				var ids = [];

				for(id in CompareMachine.productIds)
					ids.push(id);

				ids.push(pid);
				
				window.location = '/compare/' + ids.join('/');
			}
		});
	},

	autocomplete : function(query) {
		
		if(query.trim() == "") {
			
			this.revertToPopular();
			return;
		}

		var pids = [];

		for(id in this.productIds)
			pids.push(id);

		var parameters = {
			'action' 	: 'compareAutocomplete',
			'isAjax'	: true,
			'pids'		: pids.join(','),
			'q'			: query.trim(),
			'c'			: this.listCid
		};

		new Ajax('post', {
			
			'encoding' : 'utf-8',
		
			onSuccess : function()	{

				var response = this.responseJSON;

				if(parseInt(response.res.faultCode) > 0)
					alert('Σφάλμα: ' + response.res.faultString);
				else
					CompareMachine.showAutoCompleteResults(response.res.html);
			},
		
			'parameters' : parameters
		
		}).send();
	},

	revertToPopular : function() {
	
		this.compareClear && this.compareClear.hide();
		this.resultsElement && this.resultsElement.hide();

		$('selectandadd') && $('selectandadd').show();	
	},

	showAutoCompleteResults : function(resultsHTML) {
		
		if(resultsHTML == '')
			return;

		this.compareClear 	= this.compareClear || $C('div', { 'id' : 'compare-clear', 'title' : 'Καθαρισμός αναζήτησης' }).injectIn($('searchandadd').getParent()).addEvent('click', function() { $('searchandadd').setValue('').focus(); CompareMachine.revertToPopular(); });
		this.resultsElement = this.resultsElement || $C('div', { 'id' : 'autocomplete-results' }).injectAfter(($('selectandadd') ? $('selectandadd') : $('wrapper').getElement('.searchandadd'))).setClass('selectandadd');

		$('selectandadd') && $('selectandadd').hide();

		this.resultsElement.setHTML(resultsHTML).show();
		this.compareClear.show();
		this.attachAddHandlerToProductListing(this.resultsElement);
	},

	attachCompareHandler : function(product, inProductPage) {
		
		var cid = parseInt($(product).getProperty('data-cid'));

		if(this.eligibleCats.indexOf(cid) === -1)
			return;

		if(this.compareStruct.cid > 0 && this.compareStruct.cid != cid) {

			$(product).compareElement && $(product).compareElement.remove();
			$(product).compareElement = null;

			return;
		}

		var id = parseInt($(product).getProperty('data-pid'));

		if(id == 0 || isNaN(id))
			return;

		if(typeof this.compareStruct.products[id] != "undefined" || this.enumList() == this.limit) {
	
			$(product).compareElement && $(product).compareElement.remove();
			$(product).compareElement = null;
			
			return;
		}

		if($(product).compareElement)
			return;

		var img 	= (inProductPage ? $('item-img').getElement('img').getProperty('src') : $(product).getElement('img').getProperty('src'));
		var title 	= (inProductPage ? ($('item-header').innerText ? $('item-header').innerText : $('item-header').textContent) : ($(product).getElement('h4 a').innerText ? $(product).getElement('h4 a').innerText : $(product).getElement('h4 a').textContent));
		var url 	= (inProductPage ? window.location.pathname : $(product).getElement('h4 a').getProperty('href'));

		$(product).compareElement = $C('a')
									.setClass('compare-icon')
									.setProperties({ 'href' : 'javascript:void(0);', 'title' : 'Προσθήκη του προϊόντος στη λίστα σύγκρισης' })
									.setHTML('<em>&nbsp;</em><span>Σύγκριση</span>')
									.injectIn((inProductPage ? $(product) : $(product).getElement('.img')))
									.addEvent('click', function() { 

										ItemTour.tour && ItemTour.tour.finish();
										
										ImageZoomer.popup && $(ImageZoomer.popup) && $(ImageZoomer.popup).remove();

										CompareMachine.addToList(id, cid, title, img, url);
									});
	},

	attachToProduct : function() {
		
		if(!$('page-item'))
			return;

		this.attachCompareHandler($('item-header'), true);
	},

	scanAndAttach : function() {
		
		var tableCells = $('wrapper').getElements('table.products td');

		if(tableCells.length == 0)
			return;

		tableCells.each(function() { CompareMachine.attachCompareHandler(this); });
	},

	enumList : function() { var length = 0; for(i in this.compareStruct.products) { length++; } return length; },

	saveList : function(dontSave) {
		
		if(typeof dontSave == "undefined") {

			var jsonList = JSON.stringify(this.compareStruct);

			if(!window.safari && typeof localStorage != 'undefined')
				localStorage['compare'] = jsonList;
			else
				Cookie.set('compare', jsonList);
		}

		// Render the compare tables
		this.buildFixedCompareTable();
		this.buildHeaderCompareText();

		// Scan items and remove the button for those of different category
		this.scanAndAttach();
		this.attachToProduct();

		if($('page-compare'))
			window.location = this.buildCompareURI();
	},

	addToList : function(id, catId, title, imgUrl, prodUrl) {
		
		// Reload the list just in case
		this.loadList();

		// Check if it can be added (via catId)
		if(this.compareStruct.cid > 0 && this.compareStruct.cid != catId) {
			
			alert("Δεν μπορείς να συγκρίνεις μήλα με πορτοκάλια! Η σύγκριση πρέπει να γίνεται ανάμεσα σε προϊόντα της ίδιας κατηγορίας! :)");
			this.saveList();

			return;
		}

		// If there are already max items in the list, don't add more
		if(this.enumList() == this.limit) {
		
			alert("Μπορείς να συγκρίνεις μέχρι " + this.limit + " προϊόντα!");
			return;	
		}

		// Does it already exists?
		if(this.compareStruct.products[id])
			return;

		// Add it
		if(this.compareStruct.cid == 0)
			this.compareStruct.cid = catId;

		this.compareStruct.products[id] = {
			'title' : title,
			'img'	: imgUrl,		
			'url'	: prodUrl
		};

		this.flash = true;

		// Save the list
		this.saveList();
	},

	removeFromList : function(id) {
		
		// Reload the list just in case
		this.loadList();

		// Doesn't it exist?
		if(typeof this.compareStruct.products[id] == 'undefined') {

			this.saveList(true);
			return;
		}

		// Delete it
		delete this.compareStruct.products[id];

		if(this.enumList() == 0)
			this.compareStruct.cid = 0;

		this.flash = true;

		// Save the list
		this.saveList();
	},

	clearList : function() {
		
		// Reset the list
		this.compareStruct = {
			'cid'		: 0,
			'products'	: {}
		};

		this.flash = true;

		// Save the list
		this.saveList();
	},

	buildCompareURI : function() {
	
		var ids  = [];

		for(id in this.compareStruct.products)
			ids.push(id);

		return '/compare/' + ids.join('/');
	},

	buildFixedCompareTable : function() {

		if($('page-compare'))
			return;
			
		this.fixedTable && this.fixedTable.remove();
		this.fixedTable = null;

		if(this.enumList() == 0)
			return;

		this.fixedTable = $C('div', { 'id' : 'compare-fixed' }).injectIn(document.body);

		var html = '';

		html += '<p class="compare">';
		html += '<a class="cmp" title="' + (this.enumList() == 1 ? 'Προσθήκη για σύγκριση' : 'Σύγκριση') + '" href="' + this.buildCompareURI() + '">Σύγκριση</a>';
		html += '<a class="del" title="Αφαίρεση όλων" href="javascript:void(0);" onclick="CompareMachine.clearList();">Αφαίρεση</a>';
		html += '</p>';
		html += '<table>';

		for(id in this.compareStruct.products) {
			
			var product = this.compareStruct.products[id];

			html += '<tr><td><div>';
			html += '<a href="' + product['url'] + '"><img width="64" height="64" src="' + product['img'] + '"/></a>';
			html += '<p><a href="' + product['url'] + '">' + product['title'] + '</a></p>';
			html += '<a title="Αφαίρεση από την λίστα σύγκρισης" href="javascript:void(0);" class="remove" onclick="CompareMachine.removeFromList(' + id + ')">Αφαίρεση</a>';
			html += '</div></td></tr>';
		}

		if(this.limit - this.enumList() > 0) {

			html += '<tr><td class=\"pale\">';
			html += '<p>Μπορείς να προσθέσεις ' + (this.limit - this.enumList() == 1 ? 'άλλο 1 προϊόν' : 'άλλα ' + (this.limit - this.enumList()) + ' προϊόντα') + '.<br/><a href="' + this.buildCompareURI() + '">Γρήγορη επιλογή</a></p>';
			html += '</td></tr>';
		}

		html += '</table>';

		this.fixedTable.setHTML(html);
	},

	buildHeaderCompareText : function() {

		var flash = this.flash;
				
		this.flash = false;

		this.fixedHeader && this.fixedHeader.remove();
		this.fixedHeader = null;

 		if(this.enumList() == 0) {

 			$('login-container').removeClass('fixed');
			$('login-container').getElement('.santa-header') && $('login-container').getElement('.santa-header').show();
			return;
		}

		$('login-container').addClass('fixed');
		$('login-container').getElement('.santa-header') && $('login-container').getElement('.santa-header').hide();

		this.fixedHeader = $C('div', { 'id' : 'compare-header' }).injectIn($('login-container'));

		var html = '';

		html = '<a href="' + this.buildCompareURI() + '">Συγκριση (' + this.enumList() + ')</a>';

		this.fixedHeader.setHTML(html);

		if(flash) {

			new Fx.Style(this.fixedHeader, 'opacity', { 

				'duration' 		: 200, 
				'onComplete' 	: function() {
				
					if(!CompareMachine.fixedHeader)
						return;

					new Fx.Style(CompareMachine.fixedHeader, 'opacity', { 

						'duration' 		: 200 
					}).start(0, 1);
						
				} 
			}).start(1, 0);
		}
	}
}

SwitchToMobile = {
	
	initialize : function() {
		
		if(!$('switch-mobile'))
			return;

		$('switch-mobile').addEvent('click', function() {
		
				Cookie.set('switchdesktop', '');
				window.location.reload();
		});
	}
}

ContactForm = {
	
	initialize : function() {

		if(!$('contact-form'))		
			return;

		$('contact-form').addEvent('submit', function(event) {
			
			event.stop();

			var feedback = $('contact-feedback').value.trim(), self = this;

			if(!feedback) {
				
				alert('Δώσε κείμενο για να συνεχίσεις.');
				$('contact-feedback').focus();

				return false;
			}

			var email = $('contact-email').getValue();

			if(!email || !email.isValidEmail()) {
				
				alert('Πρέπει να συμπληρώσεις ένα έγκυρο email για να μπορέσουμε να επικοινωνήσουμε μαζί σου αργότερα.');
				$('contact-email').focus();

				return false;
			}

			var parameters = {
				'action' 	: 'submitFeedback',
				'isAjax'	: true,
				'feedback'	: feedback.replace('Η άποψή σου για το BestPrice', '').trim(),
				'email'		: $('contact-email').getValue(),
				'name'		: ($('contact-name') ? $('contact-name').getValue() : ""),
				'tel'		: ($('contact-tel') ? $('contact-tel').getValue() : ""),
				'url'		: ($('contact-url') ? $('contact-url').getValue() : ""),
				'iscritic' 	: ($('contact-iscritic') ? 1 : 0),
			};
		
			new Ajax('post', {
				
				'encoding' : 'utf-8',
			
				onSuccess : function()	{
				
					var response = this.responseJSON;

					if(parseInt(response.res.faultCode) > 0)
						alert('Σφάλμα: ' + response.res.faultString);
					else {
						
						alert('Σε ευχαριστούμε για την επικοινωνία.\n\n-Η ομάδα του Bestprice.gr');

						$('contact-email').setValue('');
						$('contact-feedback').setValue('');

						$('contact-name') && $('contact-name').setValue('');
						$('contact-tel') && $('contact-tel').setValue('');
						$('contact-url') && $('contact-url').setValue('');
					}
				},
			
				'parameters' : parameters
			
			}).send();
		});
	}
}

ContactOverlay = {
	
	initialize : function() {

		if(!$('contact-overlay'))
			return;

		this.overlay 	= new Overlay('', {
			'onOpen'	: function() 	{ this.element.addClass('overlay-normal'); },
			'beforeClose': function() 	{ this.element.removeClass('overlay-normal'); }
		});

		$('contact-overlay').addEvent('click', function(event) {
			
			event.stop();

			ContactOverlay.openOverlay();
		})
	},

	openOverlay : function() {
		
		var html = [];

		html.push('<div class="overlay-inner">');
		
		html.push('<div class="overlay-header">');
		html.push('<h4>Επικοινώνησε μαζί μας!<span class="close" onclick="ContactOverlay.overlay.close();">x</span></h4>');
		html.push('</div>');
		
		html.push('<div class="overlay-body clr">');

		html.push('<ul class="contact-choices">');

		html.push('<li class="merchant">');
		html.push('<a href=\"/about/join\">');
		html.push('<em></em>Έχω ηλεκτρονικό κατάστημα και θέλω να συνεργαστώ με το BestPrice');
		html.push('</a>');
		html.push('</li>');

		html.push('<li class="critics">');
		html.push('<a href=\"/about/critics\">');
		html.push('<em></em>Είμαι πάροχος περιεχομένου και θέλω να συνεργαστώ με το Bestprice');
		html.push('</a>');
		html.push('</li>');
		
		html.push('<li class="user">');
		html.push('<a href=\"/about/contact\">');
		html.push('<em></em>Θέλω να επικοινωνήσω με το BestPrice');
		html.push('</a>');
		html.push('</li>');

		html.push('</ul>');
				
		html.push('</div>');	
		html.push('</div>');
		
		this.overlay.open(html.join(''));
		this.overlay.element.setStyle('z-index', '99999999');
		this.overlay.pos();	
	}
}

/* Include the objects that will be reinitialized in every push state request here */
Objects = [
	Nearby
	,SearchFeedback
	,CategorySearch
	,SearchBox
	,CreateAccount
	,LoginRegisterBox
	,Alerts
	,Welcome
	,ChangeAvatar
	,ItemRating
	,ReviewForm
	,MerchantReviewForm
	,Reviews
	,MerchantMap
	,JoinNetwork
	,ReviewIt
	,Product
	,Gallery
	,Tips
	,ProductsExpander
	,Adult
	,ReadTerms
	,PageIframe
	,WelcomeBox
	,Filters
	,CloseSuggestion
	,MoreSecondaryCats
	,ScrollItem
	,MyLocation
	,PriceDrop
	,WantHave
	,Wishlist
	,Havelist
	,PriceHistory
	,Carousel
	,DealsSubscribe
	,ClickBadge
	,ToggleFollow
	,FollowersTicker
	,BigImage
	,StreamMore
	,Invite
	,SaveSettings
	,BadgeGenerator
	,CartMachine
	,ItemFilter
	,ItemSort
	,AutoPublish
	,ReviewReply
	,ImageZoomer
	,SantaTerms
	,UserFeed
	,SubTabs
	,OverlayOpener
	,FilterWishlist
	,BBSlideshow
	,CompareMachine
	,ItemTour
	,SwitchToMobile
	,ContactForm
	,ContactOverlay
];

document.addEvent("DOMContentLoaded", function() {

	Objects.each(function() { this.initialize(); });

	// Add the object which need only 1 initialization here 
	// (e.g. objectss that reside only in header like UserMenu, or
	// objects that need to be initialized just once cause they are awesome like Pageles)
	[
	CategoriesHeader,
	UserMenu,
	Pagelet
	].each(function() { this.initialize(); });
});

if(window.Tip) {
	Tip.setOptions({ 'followMouse' : true});
}

if(screen.height <= 768)
	document.write('<style>#page-home #wrapper { padding-top: 5px!important; } #page-home .main-categories-box { padding-top: 45px!important; padding-bottom: 10px!important; } #page-home h1 { margin-bottom: 20px!important;}</style>');
