Ajax.Responders.register({
	onCreate: function() {
		$('loader').update('Loading ...');
		$('loader').removeClassName('hidden');
		if($('loader') && Ajax.activeRequestCount > 0) Effect.Appear('loader',{duration: 0.25, queue: 'end'});
	},
	onComplete: function() {
		if($('loader') && Ajax.activeRequestCount == 0) Effect.Fade('loader',{duration: 0.25, queue: 'end'});
	}
});

var timer = null;
Event.observe(window, 'load', function() {

	if($('advancedSearch') != null){
		$('advancedSearch').observe('click',function(event){
			Event.stop(event);
			var element = Event.element(event);
			new Effect.toggle(element.next(),'blind',{duration: 0.5});
			//element.addClassName('opened');
			if(element.hasClassName('opened')){
				element.removeClassName('opened');
				element.update("Advanced search");
			}else{
				element.addClassName('opened');
				element.update("Advanced search");
			}
		});
	}
		
	if($('showcase') != null) var sc = new necShowcase();
	if($('newsbrowser') != null) var sc = new necNewsbrowser2();
	
	
	$$('a.enlarge').invoke('observe','click',function(event){
		Event.stop(event);
		var element = Event.element(event);
		if(element.hasClassName('features')) var enlarge = new enlargeItem(element);
		else if(element.hasClassName('tags')) var enlarge = new showTags(element);
		else if(element.hasClassName('endpoint')) var enlarge = new enlargeImage(element);
		else if(element.hasClassName('embedFlash')) var enlarge = new embedFlash(element);	
	});
	
	var dd = new NECdropper().init();
	
	$$(".productContainer img").invoke('observe','mouseover',function(event){
		var element = Event.element(event);
		var wrapper = element.up(2);
		var glance 	= new showGlance(wrapper,'browser');
	});


	$$('.gallery img').invoke('observe','click',function(event){
		var element = Event.element(event);
		var swapper = new impressionMover(element);
	});
	
	$$('.impression img').each(
		function(image){
			new Effect.Appear(image);
		}
	);
	
	$$('.enlargeImage').invoke('observe','click',function(event){
		var el = Event.element(event);
		if(el.tagName == "IMG" && !el.id) var ef = new enlargeImageInline(el);
		else var ef = new embedFlash(el); 
	});
	
	
	
	
	if($('news') != null) var nws = new necNewsBrowser();
	if($('endpointGallery') != null) var epg = new endpointBrowser();

	if($('chooseLanguage') != null) var lang = new showNECLanguages();
	var i = 0;
	$$(".video").each(function(el){
		el.update("<div id='embed"+i+"'></div>");
		var flashvars = {};
		var params = {};
		var attributes = {};
		var swf = swfobject.embedSWF("flash/"+el.id, "embed"+i, "660", "370", "8.0.0", false, flashvars, params, attributes);	
		i++;
	});
});
var enlargeImageInline = Class.create({

	initialize: function(element) {
		this.element	= element;
		this.image_id	= element.src.split("/").last();
		
		this.lightbox 	= new overlay();	
		this.updateBox();
	},
	updateBox: function(){
		$('overlayBox').addClassName("image");
		
		var inner 	= "<div class='btop'></div><a href='#' class='close'>close</a><img src='impressions/xl-"+this.image_id+"'><div class='bbottom'></div>";
		this.lightbox.updateOverlay(inner);
		
		this.observeClose();
	
	},
	observeClose: 	function(){
		$$('#overlayBox .close').invoke('observe','click',function(event){
			Event.stop(event);
			this.lightbox.closeOverlay();
		}.bind(this));
	}
});
var necNewsbrowser2 = Class.create({
	initialize: function(){
		this.newsbrowser 	= $("newsbrowser");
		this.nbs			= $$("#newsbrowser .swapper li");
		this.nbsCount		= this.nbs.length;
		this.counter		= 0;
		
		this.currentItem 	= this.nbs[this.counter];
		this.nextItem 		= this.nbs[this.counter+1];
		
		this.duration 		= 0.5;
		this.timeout 		= 4000;
		this.timer 			= null;
		this.setTimer();  
	},
	setTimer: function(){
		this.timer = setTimeout(this.update.bind(this),this.timeout);
	},
	update: function(){
		clearInterval(this.timer);
		this.timer = null;
		
		new Effect.Fade(this.currentItem,{
			duration:this.duration,
			afterFinish: function(){
				this.showNext();
			}.bind(this)
		});
	},
	showNext: function(){
		new Effect.Appear(this.nextItem,{
			duration:this.duration,
			afterFinish: function(){
				this.counter++;
								
				this.currentItem 	= this.nextItem;
				if(this.counter == this.nbsCount) this.counter = 0;
				this.nextItem 		= this.nbs[this.counter];

				this.timer = setTimeout(this.update.bind(this),this.timeout);				
			}.bind(this)
		});
	
		
	}
	
});
var NECdropper = Class.create({
	initialize: function(){
		this.dropliciousShowingUpDuration 	= 0;
		this.dropliciousHidingDuration 		= 0;
		this.dropliciousHideDelay 			= 0;
	},
	init: function(){
		$$('a.drops').each(function(name){
			name.observe('mousemove', this.linkMouseOver.bindAsEventListener(this));
			name.observe('mouseout', this.linkMouseOut.bindAsEventListener(this));
		}.bind(this));

		$$('ul.subs').each(function(name){
			name.observe('mousemove', this.submenuMouseOver.bindAsEventListener(this));
			name.observe('mouseout', this.submenuMouseOut.bindAsEventListener(this));
		}.bind(this));
	},
	linkMouseOver: function(id){
		var dropElement = id.element().next();
		if(dropElement){
			if (!dropElement.hasClassName('hidding')){
				dropElement.removeClassName('waitingtohide');
			}
			if (!dropElement.hasClassName('active')){
				dropElement.addClassName('active');
				this.dropliciousShowingUpEffect(dropElement);
			}
		}
	},
	linkMouseOut: function(id){
		var dropElement = id.element().next();		
		if (dropElement && dropElement.hasClassName('active')){
			this.setDelayedHide(dropElement);
		}
	},
	dropliciousShowingUpEffect: function(element){
		if(!element.visible()){
			new Effect.BlindDown(element, {
				duration: this.dropliciousShowingUpDuration,
				queue: {
					position: 'end',
					scope: element.identify(),
					limit:2
				}
			});
		}
	},
	dropliciousHidingEffect: function(element){
		new Effect.BlindUp(element, {
			duration: this.dropliciousHidingDuration,
			queue: {
				position: 'end',
				scope: element.identify(),
				limit: 2
			}
		 });
	},
	setDelayedHide: function(element){
		element.addClassName('waitingtohide')
		if(!element.hasClassName('hidding')){
			if (!element.hasClassName('hiddingtimerset')){	
				element.addClassName('hiddingtimerset');
				setTimeout(
					function(){ 
						this.delayedHide(element);
					}.bind(this), this.dropliciousHideDelay * 1000);
			}
		}
	},
	delayedHide: function(dropElement){
		dropElement.removeClassName('hiddingtimerset');
		if (dropElement.hasClassName('waitingtohide')){
			this.dropliciousHidingEffect(dropElement);
			dropElement.addClassName('hidding');
			setTimeout(
				function(){
					dropElement.removeClassName('waitingtohide');
					dropElement.removeClassName('hidding');
					dropElement.removeClassName('active');
				}, this.dropliciousHidingDuration * 1000);
		}
	},
	submenuMouseOut: function(event){
		var dropElement = event.findElement("ul");	
		if (dropElement && dropElement.hasClassName('active')){
			this.setDelayedHide(dropElement);

		}
	},
	submenuMouseOver: function(event){
		var dropElement = event.findElement("ul");	
		if (dropElement && !dropElement.hasClassName('hidding')){
			dropElement.removeClassName('waitingtohide');
		}
	}
});

// general contact form
function sendGeneralForm(){
	
	var inputs 		= $('gereralContacts').getInputs('text');
	var form_values = $('gereralContacts').serialize(true);
	var reg 		= /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var missed 		= false;
	var falseMail	= false;
	var mailCheck 	= "";
	var fieldCheck	= "";
	inputs.each(function(i){
		
		if(i.hasClassName("req") && i.hasClassName("email") && reg.test($F(i)) == false){
			i.addClassName("missed");
			falseMail 	= true;
			mailCheck 	= "<br /><span>!</span> The E-mail address you have entered is not valid.";
		}
		else if(i.hasClassName("req") && $F(i) == ""){
			i.addClassName("missed");
			missed 		= true;
			fieldCheck 	= "<span>!</span> You did not fill in all the required fields. Please fill in the fields marked in blue.";
		}else i.removeClassName("missed");

	});
	
	if(missed == true || falseMail == true){
		$('msg').update(fieldCheck+mailCheck);
		return false;
	}
	
	
	new Ajax.Request('forms/handle_general_inquiries.php',{
		parameters: form_values,
		onComplete: function () {
			var upd = "<h4>The form has been sent.</h4><p>Thank you for your information request, NEC Unified Solutions will contact you within 24 hours.<br />An email has been sent to "+$F('email')+" with a confirmation of your request.</p>";
			$('gereralContacts').update(upd);
			
			new Effect.Highlight('gereralContacts',{startcolor:"#cccccc",endcolor:"#ffffff", duration:1.5, delay:0.5});
		}
	});
}

// partner boarding form
function partnerBoarding(){
	
	var inputs 		= $('businessBoarding').getElements();
	var form_values = $('businessBoarding').serialize(true);
	var reg 		= /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/;
	var missed 		= false;
	var falseMail	= false;
	var mailCheck 	= "";
	var fieldCheck	= "";
	inputs.each(function(i){
		
		if(i.hasClassName("req") && i.hasClassName("email") && reg.test($F(i)) == false){
			i.addClassName("missed");
			falseMail 	= true;
			mailCheck 	= "<br /><span>!</span> The E-mail address you have entered is not valid.";
		}
		else if(i.hasClassName("req") && $F(i) == ""){
			i.addClassName("missed");
			missed 		= true;
			fieldCheck 	= "<span>!</span> You did not fill in all the required fields. Please fill in the fields marked in blue.";
		}else i.removeClassName("missed");

	});
	
	if(missed == true || falseMail == true){
		$('msg').update(fieldCheck+mailCheck);
		return false;
	}
	
	
	new Ajax.Request('forms/handle_partner_boarding.php',{
		parameters: form_values,
		onComplete: function () {
			var upd = "<h4>The form has been sent.</h4><p>Thank you for your information request, NEC Unified Solutions will contact you within 24 hours.</p>";
			$('msg').update(upd);
			$('partnerSendBtn').disabled = true;
		}
	});
	
}

// country autocomplete
function completeCountries(){
	new Ajax.Autocompleter('country','countries', "forms/get_global_countries.php", {
		paramName: "ct"
	});
}

//get partners from country
function showPartners(lang,lbl){
	
	var country = lang.replace("country=","");
	new Ajax.Request("pages/global/get_partners.php",{
		parameters: "country="+country+"&lbl="+lbl,
		onComplete:function(transport){
			
			var resp = transport.responseText;
			$('country').update(resp);
			new Effect.ScrollTo('country');
			
		}.bind(this)
	});
		
}
// language dropwdown
var showNECLanguages = Class.create({
	initialize: function() {
		this.element		= $('langSelector');
		this.duration		= 0.5;
		this.timeOut		= 500;
		this.timer			= null;
		this.observeMouse();			
	},
	observeMouse : function(){
		$('chooseLanguage').observe("mouseover",this.showLangList.bind(this));
		$('chooseLanguage').observe("mouseout",this.createTimeout.bind(this));
	},
	createTimeout: function(){
			
		this.timer = setTimeout(function(){
			this.timer = null;
			clearInterval(this.timer);
			this.observeMouseOut();
			$('chooseLanguage').stopObserving("mouseout");
		}.bind(this),this.timeOut);	
		
	},
	showLangList: function(){
		$('chooseLanguage').stopObserving("mouseover");
		
		this.element.show();
		//new Effect.SlideDown(this.element,{duration:this.duration,
		//	afterFinish: function(){
		//	}.bind(this)	
		//});
	},
	observeMouseOut: function(){
			
		//set timeout for hovering to dropdown div
		this.timer 	= setTimeout(function(){

			document.observe('mouseover', function(event){
				var element = Event.element(event);	
				if (element.descendantOf(this.element) == false){
					this.hideLangList();			
					document.stopObserving('mouseover');
					this.observeMouse();
				}
			}.bind(this));

		}.bind(this),200);
		
	},
	hideLangList: function(){
		this.element.hide();
		//new Effect.SlideUp(this.element,{duration:this.duration});
	}	
});

// end point browser
var endpointBrowser = Class.create({
	initialize: function() {
		
		//this.direction 		= dir; 
		this.effectTime		= 0.5;
		this.wrapper		= $('endpointGallery');
		this.mover			= this.wrapper.down().next(1).down();
		this.itemCount		= $$("#endpointGallery img").length;
		this.maxClick		= Math.floor(this.itemCount/6);
		this.leftClick		= this.wrapper.down();
		this.rightClick		= this.wrapper.down().next();
		this.currentCount	= 0;
		this.observeClicks();
						
	},
	observeClicks: function(){
		
		$$('#endpointGallery .mover').invoke('observe','click', function(event){
			var element = Event.element(event);
			if(element.hasClassName('toLeft')) this.direction = "left";
			else this.direction = "right";	
			this.moveBrowser(element);
			$$('#endpointGallery .mover').invoke('stopObserving','click');
		}.bind(this));
		
	},
	moveBrowser: function(element){
		this.checkClassNames(element);
		
		if(this.direction == "left" && this.mover.hasClassName('inactive')) return;
		this.movePx = (this.direction == "left") ? 600 : -600;
		if(this.currentCount == 0 && this.direction == "left") return;
		if(this.currentCount == this.maxClick && this.direction == "right") return;
		
		
		new Effect.Move (this.mover,{ y: 0, x: this.movePx, duration:this.effectTime, mode: 'relative',
			afterFinish: function(){
				
				this.mover.removeClassName('start');
				if(this.direction == "left") this.currentCount--;
				else this.currentCount++;
				
				this.observeClicks();
				
				
			}.bind(this)
		});	
	},
	checkClassNames: function(){
		
		if(this.currentCount == this.maxClick -1 && this.direction == "right"){
			this.rightClick.addClassName("inactive");
			this.leftClick.removeClassName("inactive");	
		}
		if(this.currentCount == 1 && this.direction == "left"){
			this.rightClick.removeClassName("inactive");
			this.leftClick.addClassName("inactive");
		}
		
	}
});

// home showcase
var necNewsBrowser = Class.create({
	initialize: function() {
		this.newsContainer 	= $('news'); 
		this.timeOut		= 10000;
		this.effectTime		= 0.5;
		this.newsCounter	= 0;
		this.newsTotal		= $$("#newsSelector span").length;
		this.newsTimer 		= null;
		this.paused			= false;
		this.currentNews	= this.newsContainer.down();
		this.nextNews		= this.newsContainer.down().next();
		this.observeClicks();
		this.createInterval();
					
	},
	fadeCurrentNews: function(loadClicked){
		new Effect.Fade(this.currentNews,{
			duration:this.effectTime,
			afterFinish:function(){
				this.showNext(loadClicked);
			}.bind(this)
		});
	},
	showNext: function(loadClicked){
		if(loadClicked !=null) this.nextNews = $("nb"+loadClicked);
		if(loadClicked == null) this.updateSelector();
		
		new Effect.Appear(this.nextNews,{
			duration:this.effectTime,
			afterFinish:function(){
				if(this.paused == false) this.createInterval();
				this.updateItems()
			}.bind(this)
		});
	},
	updateItems: function(){
		this.currentNews	= this.nextNews;
		this.nextNews		= this.newsContainer.down().next(this.newsCounter);
		// reset to first
		if((this.newsCounter+1) >= this.newsTotal) this.nextNews = this.newsContainer.down();
	},
	createInterval: function(){
		this.newsTimer = setTimeout(function(){
			this.fadeCurrentNews();
			this.newsTimer = null;
			clearInterval(this.timer);
		}.bind(this),this.timeOut);
	},
	updateSelector: function(){
		
		$$("#newsSelector span").invoke('removeClassName','active');
		if(this.paused == true){
			if(this.newsCounter == 0) $("newsSelector").down().addClassName("active");
			else $("newsSelector").down().next(this.newsCounter).addClassName("active");
		}
		else if( (this.newsCounter+1) >= this.newsTotal ){
			this.newsCounter = 0;
			$("newsSelector").down().addClassName("active");
		}else{
			$("newsSelector").down().next(this.newsCounter).addClassName("active");
			this.newsCounter++;
		}
		
	},
	observeClicks: function(){
	
		$$("#newsSelector span").invoke('observe','click',function(event){
			var element = Event.element(event);
					
			//clear timeout
			clearTimeout(this.newsTimer);
			this.newsTimer 	= null;
			var loadClicked = element.id.replace("sel","");
			
			this.fadeCurrentNews(loadClicked);
			this.paused 	= true;
			
			$$(".selector span").invoke('removeClassName','active');
			element.addClassName("active");
		 
		}.bind(this));
	}
});

//embed flash via swfobject
var embedFlash = Class.create({
	initialize: 	function(element) {
		this.element	= element;
		this.overlay 	= new overlay();
		//this.div		= new Element("div",{id: "flashContent"});	
		this.flashLink	= "flash/"+this.element.id;
		this.languageId	= $("header").className;
		
		var inner 	= "<a href='#' class='close padded'>close</a><div id='flashContent'></div>";
		this.overlay.updateOverlay(inner);
		
		$$('#overlayBox .close').invoke('observe','click',function(event){
			Event.stop(event);
			this.overlay.closeOverlay();
		}.bind(this));
		
		$('overlayBox').addClassName("large");
		this.flashIt();
	},
	flashIt: function(){
		var languageId	= $("header").className;
		var base		= document.domain;
		
		
		var flashvars = {language: languageId,base: base};
		var params = {};
		params.wmode = "transparent";
		var attributes = {};
		var swf = swfobject.embedSWF(this.flashLink, "flashContent", "800", "500", "8.0.0", false, flashvars, params, attributes);
	
	
	}
});

// NEC homepage Showcase
var necShowcase = Class.create({
	initialize: 	function() {

		this.timer			= null;
		this.wrapper		= $('showcase');
		this.cases			= $('cases');
		this.currentCase 	= this.cases.down();
		this.nextCase 		= this.cases.down().next();
		this.itemCount		= $$('#cases .case').length-1;
		this.currentCount	= 0;
		this.selector		= this.cases.next();
		this.clickedItem	= null;
		this.speed			= 0.5;		
		
		this.timer = setTimeout(function(){
			this.fadeCurrent();
		}.bind(this),7000);
		
		this.observeClicks();
	},
	fadeCurrent: 	function(){
		//new debug("fade current case");		
		new Effect.Fade(this.currentCase,{
			duration:this.speed,
			afterFinish: function(){
				this.showNext();
				this.updateSelector();		
			}.bind(this)
		});
	},
	showNext: 		function(){
		//new debug("show next");		
		new Effect.Appear(this.nextCase,{
			duration:this.speed,
			afterFinish: function(){
				this.currentCase.removeClassName("active"); 
				this.nextCase.addClassName("active");
				
				this.currentCount++;
				this.createInterval();
				this.resetVars();
			}.bind(this)
		});
	},
	createInterval: function(){
		this.timer 	= setTimeout(function(){
			clearInterval(this.timer);
			this.timer = null;
			this.fadeCurrent();
		}.bind(this),7000);
	},
	resetVars: 		function(){
		if(this.currentCount == this.itemCount){
			this.currentCase 	= this.nextCase;
			this.nextCase 		= this.cases.down();
			this.currentCount	= -1;
		}else{		
			this.currentCase 	= this.nextCase;
			this.nextCase		= this.cases.down().next(this.currentCount);
		}
	},
	updateSelector: function(){
		$$('#showcase .selector span').invoke('removeClassName','active');
		if( this.currentCount == -1){
			this.selector.down().addClassName('active');
		}else{
			this.selector.down().next(this.currentCount).addClassName('active');
		}
	},
	observeClicks: 	function(){
		
		$$('#showcase .selector span').invoke('observe','click',function(event){
			//stop observer on selector
			$$('#showcase .selector span').invoke('stopObserving','click');
			
			var element = Event.element(event);
			var id		= parseInt(element.id.replace("case",""));
		
			// clear interval
			clearInterval(this.timer);
			this.timer = null;
			
			//new debug("interval cleared");		
			$$('.selector span').invoke('removeClassName','active');
			element.addClassName('active');
			
			// active case
			var activeItem 	= $$('#cases .active');
			if(id == 0) var clickedItem = this.cases.down();
			else var clickedItem = this.cases.down().next(id-1);
			
			// fade current item
			new Effect.Fade(activeItem[0] ,{
				duration:this.speed,
				afterFinish: function(){
					activeItem[0].removeClassName('active');
					clickedItem.addClassName('active');
					
					new Effect.Appear(clickedItem,{
						duration:this.speed,
						afterFinish: function(){
							//start observing selector clicks
							this.observeClicks();
						}.bind(this)
					});
					
				}.bind(this)
			});
			
		}.bind(this));
	
	}
});


// Images gallery (terminals)
var impressionMover = Class.create({
	initialize: 	function(element) {
		this.element		= element;
		this.wrapper		= this.element.up().previous();
		this.itemCount		= $$(".gallery img").length-1;
		this.position 		= parseInt(this.element.id.replace("pos-",""));
		this.updateThumbs();
	},
	updateThumbs: 	function(){
		$$(".gallery img").invoke("removeClassName","active");
		this.element.addClassName("active");
		this.moveImpression();
	},
	moveImpression: function(){
		
		var xPos = -1 * 665 * this.position;
		new Effect.Move (this.wrapper,{ y: 0, x:xPos , duration:0.7, mode: 'absolute'});
		
	}
});

// tag cloud
var showTags = Class.create({
	initialize: 	function(element) {
		this.element	= element;
		if($('tagBlock') == null) this.createWrapper();
		else{
			new Effect.Appear('tagBlock',{duration:0.5});
		}
	},
	createWrapper: 	function(){
		this.updateDiv = new Element('div',{id: 'tagBlock' }).hide(); //update('<div class="btop"></div> <div class="bbottom"></div>');			
		$$("body").first().insert(this.updateDiv);
		this.getTags();
	},
	getTags: 		function(){
		new Ajax.Request("pages/global/all_tags.php",{
			onComplete:function(transport){
				
				var resp = transport.responseText;
				var inner = "<div class='btop'></div><a href='#' class='close'>close</a>"+resp+"<div class='bbottom'></div>";
				this.updateDiv.update(inner);
			//	Cufon.replace('h4.cf');
				this.positionItem();

			}.bind(this)
		});
	},
	positionItem: 	function(){
		var th 			= this.updateDiv.getHeight();
		var clickPos 	= this.element.cumulativeOffset();
		this.updateDiv.setStyle({
			top: (clickPos[1]-th-35) + 'px',
			marginLeft: -225 + 'px'
		});
		
		this.showItem();
	},
	showItem: 		function(){
		//this.updateDiv.show();
		new Effect.Appear(this.updateDiv,{duration:0.5});
		this.observeClose();
	},
	observeClose: 	function(){
		$$('#tagBlock .close').invoke('observe','click',function(event){
			Event.stop(event);
			//$('tagBlock').hide();
			new Effect.DropOut('tagBlock');
		});
	}
});

// glance text (depricated)
var showGlance = Class.create({
	initialize: 	function(element,place){
		this.timer		= null;
		this.element	= element;
		this.place 		= place;
		this.pars	 	= this.element.id.replace("glance-","");
		this.startTimer();
	},
	startTimer: 	function(){
		this.timer 	= setTimeout(function(){
			this.createWrapper();
		}.bind(this),150);
	
		this.element.observe('mouseout',function(){
			this.stopTimer();
		}.bind(this));
	},
	stopTimer: 		function(){
		clearInterval(this.timer);
		this.timer = null;
	},
	createWrapper: 	function(){
		this.updateDiv = new Element('div',{id: 'glanceBlock' }).hide();	
		$$("body").first().insert(this.updateDiv);

		//position for products
		if(this.place == 'product'){
			var parentPos	= this.element.up().positionedOffset();
			var bodyPos 	= $('glance').cumulativeOffset();
			
			this.updateDiv.setStyle({
				top: (bodyPos[1]+parentPos[1]+80) + 'px',
				left: (bodyPos[0]+parentPos[0]-20) + 'px'
			});
			
		}
		//position for product browser
		else{
			//var parentPos	= this.element.up(2).cumulativeOffset();
			var pos			= this.element.cumulativeOffset();			
			this.updateDiv.setStyle({
				top: (pos[1]+100) + 'px',
				left: (pos[0]) + 'px'
			});
		}
		

		this.getGlanceText();
	},
	getGlanceText: 	function(){
		new Ajax.Request("pages/global/get_glance_text.php",{
			parameters: "pars="+this.pars,
			onComplete:function(transport){
				
				this.glance = transport.responseText;
				var inner = "<div class='btop'></div><div class='wrapper'>"+this.glance+"</div><div class='bbottom'></div>";
				this.updateDiv.update(inner);
				
				Cufon.replace('h4.cf');
				
				this.updateDiv.show();
				this.observeMouseOut();
				
			}.bind(this)
		});
	},
	observeMouseOut:function(){
		this.element.observe('mouseout',function(){
			if($('glanceBlock') != null) $('glanceBlock').remove();
		}.bind(this));
	}
});

// enlarge image from enlarge item
var enlargeItem = Class.create({
	initialize: 	function(element) {
		this.element	= element;
		this.eid		= this.element.id.replace("eid_","")
		this.cn			= this.element.className.split(" ");
		this.enlargeType= this.cn[1];
		if($('enlargedBlock') == null) this.createWrapper();
		else{
			new Effect.Appear('enlargedBlock',{duration:0.5});
		}
	},
	createWrapper: 	function(){
		this.updateDiv = new Element('div',{id: 'enlargedBlock' }).addClassName('features').hide(); //update('<div class="btop"></div> <div class="bbottom"></div>');			
		$$("body").first().insert(this.updateDiv);
		var clickPos = this.element.positionedOffset();
		this.updateDiv.setStyle({
			top: (clickPos[1] +153) + 'px'
		});
		this.getEnlargedData();
	},
	getEnlargedData:function(){
		new Ajax.Request("pages/global/enlarge_item.php",{
			parameters: "eid="+this.eid+'&type='+this.enlargeType,
			onComplete:function(transport){
				this.resp = transport.responseText;
				var inner = "<div class='btop'></div><a href='#' class='close'>close</a>"+this.resp+"<div class='bbottom'></div>";
				this.updateDiv.update(inner);
				this.showItem();
			}.bind(this)
		});
	},
	showItem: 		function(){
		//this.updateDiv.show();
		new Effect.Appear(this.updateDiv,{duration:0.5});
		this.observeClose();
	},
	observeClose: 	function(){
		$$('#enlargedBlock .close').invoke('observe','click',function(event){
			Event.stop(event);
			//$('tagBlock').hide();
			new Effect.DropOut('enlargedBlock');
		});
	}
});


var productBrowser = Class.create({
	initialize: 	function(element) {
		this.element			= element;
		this.productContainer	= this.element.up(1);
		this.productWrapper		= this.productContainer.down();
		this.nextBtn 			= this.productWrapper.next();
		this.productCount		= $$("."+this.productWrapper.className+" .item").length;
		this.maxCount			= Math.floor(this.productCount/6);
		this.duration			= 0.5;
		this.positionCounter 	= 0;
		this.direction 	= 'next';
		this.movePx		= -650;
		this.moveBrowser();
		this.stopObservers();
	},
	moveBrowser: 	function(){
		new Effect.Move (this.productWrapper,{ y: 0, x: this.movePx, duration:this.duration, mode: 'relative',
			afterFinish: function(){
				this.insertPrevButton();
				this.positionCounter++;
				this.checkPosition();
				this.observeButtons();
			}.bind(this)
		});	
	},
	insertPrevButton:function(){
		var previousButton 	= " <span class='btn'><input type='button' value='Show previous' class='observe productSlider prev' /></span>";
		this.productWrapper.next().insert({after: previousButton});
		this.prevBtn 		= this.nextBtn.next(); 
		//this.observeButtons();
	},
	observeButtons: function(){
		$$("."+ this.productContainer.className +" .btn").invoke('observe','click',function(event){
			
			this.stopObservers();
			
			var element = Event.element(event);
			if(element.hasClassName('next')){
				this.direction 	= 'next';
				this.movePx		= -650;
				this.positionCounter++;
			}else{
				this.direction 	= 'prev';
				this.movePx		= 650;
				this.positionCounter--;
			}
			new Effect.Move (this.productWrapper,{ y: 0, x: this.movePx, duration:this.duration, mode: 'relative',
				afterFinish: function(){
					this.checkPosition();
					this.observeButtons();
				}.bind(this)
			});
			
		}.bind(this));
	},
	checkPosition: 	function(){
		if(this.positionCounter == 0) this.prevBtn.hide();
		else this.prevBtn.show();		
		if(this.positionCounter == this.maxCount) this.nextBtn.hide();
		else this.nextBtn.show();
	},
	stopObservers: 	function(){
		$$("."+ this.productContainer.className +" .btn").invoke('stopObserving','click');
	}
});

var enlargeImage = Class.create({
	initialize: 	function(element) {
		this.element	= element;
		this.image_id	= element.id.replace("img-","");
		this.lightbox 	= new overlay();	
		this.getRelatedData();
	},
	getRelatedData: function(){
		$('overlayBox').addClassName("medium");
		new Ajax.Request("pages/global/enlarge_image.php",{
			parameters: "image_id="+this.image_id,
			onComplete:function(transport){
				var resp	= transport.responseText;
			//	var h1		= $$();
			//	var h2		= df;
				var inner 	= "<div class='btop'></div><a href='#' class='close'>close</a>"+resp+"<div class='bbottom'></div>";
				this.lightbox.updateOverlay(inner);
				this.observeClose();
			}.bind(this)
		});
	},
	observeClose: 	function(){
		$$('#overlayBox .close').invoke('observe','click',function(event){
			Event.stop(event);
			this.lightbox.closeOverlay();
		}.bind(this));
	}
});

var overlay = Class.create({
	initialize: 	function(element) {
		$$("body").first().insert(
	      new Element('div',{ id: 'overlay' })
	    );
		$$("body").first().insert(
	      new Element('div',{ id: 'overlayBox' })
	    );
		this.element  	= element;
		this.delay		= 2000;
		this.overlay 	= $('overlay'); 
		this.overlayBox	= $('overlayBox'); 
		this.overlayBox.hide();
		this.overlay.hide();
		this.showOverlay();
	},
	showOverlay: 	function(){
		var arrayPageSize = this.getPageSize();
		this.pageHeight = arrayPageSize[1];
		this.overlay.setStyle({ height: this.pageHeight + 'px' });
		
		new Effect.Appear(this.overlay,{duration:0.5, from:0.0, to:0.5});
		this.overlay.observe('click',this.closeOverlay.bind(this))
	},
	showInner: 		function(){
		var overlayBoxHeight = this.overlayBox.getHeight();
		var marginTop = this.pageHeight - (overlayBoxHeight+400);
		
		var arrayPageScroll = document.viewport.getScrollOffsets();
        var posTop = arrayPageScroll[1] + (document.viewport.getHeight() / 10);
		
		this.overlayBox.setStyle({ top: posTop+'px' });
		new Effect.Appear(this.overlayBox,{delay:0.6,duration:0.5});
	},
	updateOverlay: 	function(update){
		this.overlayBox.update(update);
		this.showInner();
	},
	closeOverlay: 	function(){
		new Effect.Fade(this.overlayBox,{duration:0.2, from:1, to:0.0});
		new Effect.Fade(this.overlay,{delay:0.2, duration:0.5, from:0.5, to:0.0});
		
		timer = setTimeout( function(){
			$('overlayBox').remove();
			$('overlay').remove();
		}, 600);
	},
	getPageSize: 	function(){
		var xScroll, yScroll;
		
		if (window.innerHeight && window.scrollMaxY) {	
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth; 
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
		
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
	
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}

		return [pageWidth,pageHeight];
		
	}
});

//tooltips 
var toolTip = Class.create({
	initialize: 	function(tip) {
		$$("body").first().insert(
	      new Element('div',{ id: 'toolTip' })
	    );
		this.tip  	= tip;
		this.delay	= 4000;
		this.tipDiv = $('toolTip'); 
		this.tipDiv.hide();
		this.tipDiv.update(this.tip);
		this.showTip();
	},
	showTip: 		function(){
		new Effect.Appear(this.tipDiv,{duration:0.3,delay:1});
		
		//setTimeout(function(){
		//	new Effect.Highlight(this.tipDiv,{ startcolor: '#21759B',endcolor: '#90bacd'});
		//}.bind(this),1300);
		
		//new Effect.Appear(this.tipDiv,{duration:0.3, delay:0.5});
		this.timer = setTimeout(function(){
			this.fadeTip();
		}.bind(this), this.delay );
	},
	fadeTip: 		function(){
		new Effect.Fade(this.tipDiv,{duration:0.3});
		this.timer = setTimeout( function(){
			this.tipDiv.remove();
		}.bind(this), 300);
	},
	cancelTip: 		function(){
    	if(!this.timer) return;
    	clearTimeout(this.timer);
    	this.tipDiv.remove();
  	}
});

// debug
var debug 	= Class.create({
	initialize: function(msg){
		this.msg = msg;
		this.createDiv();
	},
	createDiv: function(){
		if($('debug') == null) {
			this.debug = new Element('div',{id: 'debug'});	
			$$("body").first().insert(this.debug);
		}
		$('debug').update(this.msg);
	}
});
