var PicturePersonalityTest = Class.create();

PicturePersonalityTest.prototype = {
		
	loadedImages:-1,
	randNumbers:{},
	imageThread:null,
	currentStep:0,
	hasFatalErrors:false,
	imagesSrc:[
		['1-1.jpg','1-2.jpg','1-3.jpg','1-4.jpg','1-5.jpg','1-6.jpg','1-7.jpg','1-8.jpg','1-9.jpg','1-10.jpg','1-11.jpg','1-12.jpg','1-13.jpg','1-14.jpg','1-15.jpg'],
		['2-1.jpg','2-2.jpg','2-3.jpg','2-4.jpg','2-5.jpg','2-6.jpg','2-7.jpg','2-8.jpg','2-9.jpg','2-10.jpg','2-11.jpg','2-12.jpg','2-13.jpg','2-14.jpg','2-15.jpg'],
		['3-1.jpg','3-2.jpg','3-3.jpg','3-4.jpg','3-5.jpg','3-6.jpg','3-7.jpg','3-8.jpg','3-9.jpg','3-10.jpg','3-11.jpg','3-12.jpg','3-13.jpg','3-14.jpg','3-15.jpg'],
		['4-1.jpg','4-2.jpg','4-3.jpg','4-4.jpg','4-5.jpg','4-6.jpg','4-7.jpg','4-8.jpg','4-9.jpg','4-10.jpg','4-11.jpg','4-12.jpg','4-13.jpg','4-14.jpg','4-15.jpg'],
		['5-1.jpg','5-2.jpg','5-3.jpg','5-4.jpg','5-5.jpg','5-6.jpg','5-7.jpg','5-8.jpg','5-9.jpg','5-10.jpg','5-11.jpg','5-12.jpg','5-13.jpg','5-14.jpg','5-15.jpg'],
		['6-1.jpg','6-2.jpg','6-3.jpg','6-4.jpg','6-5.jpg','6-6.jpg','6-7.jpg','6-8.jpg','6-9.jpg','6-10.jpg','6-11.jpg','6-12.jpg','6-13.jpg','6-14.jpg','6-15.jpg'],
		['7-1.jpg','7-2.jpg','7-3.jpg','7-4.jpg','7-5.jpg','7-6.jpg','7-7.jpg','7-8.jpg','7-9.jpg','7-10.jpg','7-11.jpg','7-12.jpg','7-13.jpg','7-14.jpg','7-15.jpg'],
		['8-1.jpg','8-2.jpg','8-3.jpg','8-4.jpg','8-5.jpg','8-6.jpg','8-7.jpg','8-8.jpg','8-9.jpg','8-10.jpg','8-11.jpg','8-12.jpg','8-13.jpg','8-14.jpg','8-15.jpg'],
		['9-1.jpg','9-2.jpg','9-3.jpg','9-4.jpg','9-5.jpg','9-6.jpg','9-7.jpg','9-8.jpg','9-9.jpg','9-10.jpg','9-11.jpg','9-12.jpg','9-13.jpg','9-14.jpg','9-15.jpg'],
		['10-1.jpg','10-2.jpg','10-3.jpg','10-4.jpg','10-5.jpg','10-6.jpg','10-7.jpg','10-8.jpg','10-9.jpg','10-10.jpg','10-11.jpg','10-12.jpg','10-13.jpg','10-14.jpg','10-15.jpg'],
		['11-1.jpg','11-2.jpg','11-3.jpg','11-4.jpg','11-5.jpg','11-6.jpg','11-7.jpg','11-8.jpg','11-9.jpg','11-10.jpg','11-11.jpg','11-12.jpg','11-13.jpg','11-14.jpg','11-15.jpg'],
		['12-1.jpg','12-2.jpg','12-3.jpg','12-4.jpg','12-5.jpg','12-6.jpg','12-7.jpg','12-8.jpg','12-9.jpg','12-10.jpg','12-11.jpg','12-12.jpg','12-13.jpg','12-14.jpg','12-15.jpg']
	],

	initialize: function() {   			
		var objBody = $$('body')[0];
		objBody.appendChild(Builder.node('div',{id:'picture_personality_overlay',style:'display:none; opacity:.7;'}));		
		
		objBody.appendChild(Builder.node('div',{id:'picture_personality_loading', 'style':'display:none;'},
			[
				Builder.node('div',{id:'progressBar'}),
				Builder.node('img',{src:'/images/loading.gif'})
			]	
			));
		
		objBody.appendChild(Builder.node('div',{id:'picture_personality_test',style:'display:none;'},[ 			
			Builder.node('div',{id:'picture_personality_header'},[
				Builder.node('div',{id:'picture_personality_header_title'}),
				Builder.node('div',{id:'picture_personality_header_controls'},
				[Builder.node('a',{id:'picture_personality_header_close',href:'#'},
					[Builder.node('img',{src:'/dp_plugins/global/other/images/close_button.jpg'})]
				)]
				)
			]),
			Builder.node('div',{id:'picture_personality_content'}),
			Builder.node('div',{id:'picture_personality_footer'},[
				Builder.node('div',{id:'picture_personality_footer_stauts_bar'},
				[Builder.node('div',{id:'picture_personality_footer_stauts_slider'},' ')]
				),
					Builder.node('div',{id:'picture_personality_footer_controls'},
				[
					Builder.node('a',{id:'picture_personality_footer_new'}),
					Builder.node('a',{id:'picture_personality_footer_cancel'})				
				]
				)
			])			
		]));
		
		if($('startPersonalityPictureTest') != null)
			$('startPersonalityPictureTest').observe('click',(function(event){event.stop();this.start();}).bind(this));						
		$('picture_personality_header_close').observe('click',(function(event){event.stop();this.end();}).bind(this));		
		$('picture_personality_footer_new').observe('click',(function(event){event.stop();this.startNew();}).bind(this));		
		$('picture_personality_footer_cancel').observe('click',(function(event){event.stop();this.end();}).bind(this));		
		$('picture_personality_footer_new').innerHTML = PicturePersonalityTestOptions.anew_title;				
		$('picture_personality_footer_cancel').innerHTML = PicturePersonalityTestOptions.close_title;								
		
	},
	
	start : function(){
		if(this.hasFatalErrors){
			alert(PicturePersonalityTestOptions.fatal_error_message);
			return;
		}				
		this.currentStep = 0;		
		this.pageOffests = this.getPageSize();		
        $('picture_personality_overlay').setStyle({ width: this.pageOffests[0] + 'px', height: this.pageOffests[1] + 'px' });
		$('progressBar').innerHTML = " ";
		$('picture_personality_loading').setStyle({'display':'block','visibility':'hidden'});
		var loadingOffsets = $('picture_personality_loading').cumulativeOffset();		
		var topX =Math.max(((this.pageOffests[2]-loadingOffsets[1])/2+this.pageOffests[3]/2),0);			
		var leftX = ((this.pageOffests[0] - loadingOffsets[0])/2);
		$('picture_personality_loading').setStyle({ left:leftX+'px',top:topX+'px'});						
		$('picture_personality_loading').setStyle({'visibility':'visible'});
		new Effect.Appear($('picture_personality_overlay'), { duration: 0.15, from: 0.0, to: 0.7,afterFinish: (function(){ this.loadRecources(); }).bind(this) });										
	},
	
	startNew : function(){
		this.serverNotifyClear();
		this.currentStep = 0;
		if( this.currentStep < this.imagesSrc.length){						
			$('picture_personality_test').setStyle({display:'none'});		
			$('picture_personality_loading').show();			
			this.loadRecources();
		}
	},
	
	loadingImages : function(index){		
		if(index >= this.imagesSrc[this.currentStep].length){
			this.showBox();
			return;
		}		
		
		$('picture_personality_content').appendChild(
			Builder.node('div',{name:'picture_personality_image'},
				Builder.node('a',{href:'#'},
					Builder.node('img')
				)
			)
		);	
		
		var img = $('picture_personality_content').down('img',index);			
		
		img.onabort = (function(){
			this.checkLoadedImage(this.loadedImages+1);
		}).bind(this);
								
		img.onerror = (function(){
			if(this.imageThread != null) clearTimeout(this.imageThread);		
			this.hasFatalErrors = true;
			alert(PicturePersonalityTestOptions.fatal_error_message);			
			$('picture_personality_test').setStyle({display:'none'});		
			$('picture_personality_overlay').setStyle({display:'none'});
			$('picture_personality_loading').setStyle({display:'none'});
		}).bind(this);
		
		img.onload = (function(){
			this.attachImgEvents(img);
			this.loadingImages(index+1);					
			$('progressBar').innerHTML = (Math.round(index*100/15)+7)+'%';		
			this.loadedImages++;			
		}).bind(this);
		
		img.src = '/dp_plugins/personality_picture_test_block/images/'+this.imagesSrc[this.currentStep][this.randNumbers[index]-1];
				
		if(this.imageThread != null) clearTimeout(this.imageThread);		
		this.imageThread = setTimeout((function(){this.checkLoadedImage(index)}).bind(this),20000);
	},
	
	checkLoadedImage : function(checkIndex){
		if(this.loadedImages < checkIndex){
			alert(PicturePersonalityTestOptions.imageThreadError);			
			$('picture_personality_test').setStyle({display:'none'});		
			$('picture_personality_overlay').setStyle({display:'none'});
			$('picture_personality_loading').setStyle({display:'none'});
			this.hasFatalErrors = true;
			var a = document.URL.split("#");			
			window.location = a[0];
		}
	},
	
	attachImgEvents:function(img){
		if(img==null) return;
		img.observe('mouseover',(
				function(event){
					var elm = event.element();	
					elm.up('div').className = 'selected';
				}
			).bind(this)
		).observe('mouseout',(
				function(event){
					var elm = event.element();	
					elm.up('div').className='';
					elm.up('div').removeAttribute('class');
				}
			).bind(this)
		).observe('click',(
				function(event){
					event.stop();
					var elm = event.element();						
					if(elm.tagName != 'IMG') elm.down('img');
					this.nextStep(elm);
				}
			).bind(this)
		);
	},
	
	nextStep : function (elm){			
		$('picture_personality_test').setStyle({display:'none'});		
		$('picture_personality_loading').show();			
		this.serverNotify(elm.src);								
	},
	
	serverNotify:function(link){
		$j = jQuery.noConflict();
		$j.post("/dp_plugins/personality_picture_test_block/php/ajax.php", {'setStepData':link},
			(function(data){									
				if(data['error']){
					alert(PicturePersonalityTestOptions.fatal_error_message);
					this.hasFatalErrors = true;
					$('picture_personality_test').setStyle({display:'none'});		
					$('picture_personality_overlay').setStyle({display:'none'});
					$('picture_personality_loading').setStyle({display:'none'});
				} else if(data['load_next']){
					this.currentStep = data['load_next'];
					this.loadRecources();
				} else if(data['relocation']){					
					window.location.reload(true);
				}				
			}).bind(this),
		"json");		
	},
	
	serverNotifyClear:function(){
		$j = jQuery.noConflict();
		$j.post("/dp_plugins/personality_picture_test_block/php/ajax.php", {'clearData':true},(function(data){}),"json");		
	},
	
	calcStatusbar : function(){
		var statusbar = $('picture_personality_footer_stauts_slider');		
		var width = (this.currentStep+1)*100/(this.imagesSrc.length);		
		this.statusbarEffect(statusbar,width,10);
	},
	
	statusbarEffect: function(elm,width,delay,bid){
		e_width = parseInt(elm.getStyle('width'));	
		elm.setOpacity(.6);
		if(e_width<width && (bid == null || bid == true)){			
			elm.setStyle({'width':(e_width+1)+'%'});			
			setTimeout((function(){this.statusbarEffect(elm,width,delay, true);}).bind(this),delay);
		}else if(e_width>width){
			elm.setStyle({'width':(e_width-1)+'%'});			
			setTimeout((function(){this.statusbarEffect(elm,width,delay,false);}).bind(this),delay);		
		}else{
				elm.setOpacity(1);
				return;	
			}		
	},
	
	loadRecources : function(){
		$('picture_personality_overlay').setOpacity(.7);
		this.randNumbers = [];		
		var ranIdicator = [];
		$('progressBar').innerHTML = "0%";		
		while(this.randNumbers.length<15){
			var rNum = Math.round(1+Math.random()*14);						
			if(!ranIdicator[rNum]){						
				ranIdicator[rNum] = rNum;					
				this.randNumbers[this.randNumbers.length] = rNum;
				$('progressBar').innerHTML = (Math.round(this.randNumbers.length/2)-1)+"%";		
			}		
		}		
		var content = $('picture_personality_content');
		while(content.hasChildNodes()) content.removeChild(content.childNodes[0]);						
		this.loadedImages = -1;
		this.loadingImages(0);	
	},
	
	end:function(){	
		if(confirm(PicturePersonalityTestOptions.close_confirm_text)){
			window.location.reload(true);			
			$('picture_personality_test').setStyle({display:'none'});		
			$('picture_personality_overlay').setStyle({display:'none'});
			$('picture_personality_loading').setStyle({display:'none'});
		}
	},
	
	showBox:function(){			
		$('picture_personality_header_title').innerHTML=(this.currentStep+1)+'. '+PicturePersonalityTestOptions.step_titles[this.currentStep];					
		this.picture_personality_test_Offests = [$('picture_personality_test').getWidth(),$('picture_personality_test').getHeight()];		
		$('picture_personality_test').setStyle({left:((this.pageOffests[0]-this.picture_personality_test_Offests[0])/2)+'px',top:Math.max(((this.pageOffests[2]-this.picture_personality_test_Offests[1])/2+this.pageOffests[3]/2),0)+'px'});			
		new Effect.Appear($('picture_personality_test'), {
			duration: 0.35,
			afterFinish: (function(){ this.calcStatusbar(); $('picture_personality_loading').hide(); $('progressBar').innerHTML = "";	 }).bind(this)			
		});		
	},
	
	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){
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { 
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		
		var windowWidth, windowHeight;
		
		if (self.innerHeight) {	
			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) {
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}	
				
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else { 
			pageHeight = yScroll;
		}
			
		if(xScroll < windowWidth){	
			pageWidth = xScroll;		
		} else {
			pageWidth = windowWidth;
		}		
		return [pageWidth,pageHeight,windowHeight+(document.body.scrollTop?document.body.scrollTop:(window.pageYOffset?window.pageYOffset:0)),(document.body.scrollTop?document.body.scrollTop:(window.pageYOffset?window.pageYOffset:0))];
	}
}

