﻿/*
	Milkbox v2.1 - required: mootools.js v1.2.1 core + more: Assets
		
	by Luca Reghellin (http://www.reghellin.com) July 2008, MIT-style license.
	Inspiration Lokesh Dhakar (http://www.lokeshdhakar.com/projects/lightbox2/)
	AND OF COURSE, SPECIAL THANKS TO THE MOOTOOLS DEVELOPERS
*/

/* TODO */

var Milkbox = new Class({

	Implements:[Options,Events],
	
	options:{//set all the options here
		overlayOpacity:0.7,
		topPosition:50,
		initialWidth:250,
		initialHeight:250,
		canvasBorderWidth:'0px',
		canvasBorderColor:'#000000',
		canvasPadding:'0px',
		resizeDuration:500,
		resizeTransition:'sine:in:out',/*function (ex. Transitions.Sine.easeIn) or string (ex. 'bounce:out')*/
		autoPlay:false,
		autoPlayDelay:7,
		removeTitle:false,
		onXmlGalleries:$empty,
		onClosed:$empty,
		onFileReady:$empty,
		
		PorfolioMain:null
	},
	
	initialize: function(options){
		
		this.setOptions(options);
	//	alert("initd setOptions");
		
		this.autoPlayBkup = { autoPlayDelay:this.options.autoPlayDelay, autoPlay:this.options.autoPlay };
		this.fullOptionsBkup = {};
		this.galleries = [];
		this.families = [];
		this.loadedImages = [];//to check the preloaded images
		this.currentFile = null;
		this.currentIndex = null;
		this.currentGallery = null;
		this.currentRequest = null;
		this.currentResponse = null;
		//alert("initd currentResponse");
		this.mode = null;//'singleFile','fileGallery'
		this.closed = true;
		this.busy = true;//to control keyboard and autoplay events
		this.paused = true;
		this.fileReady = false;//to prevent overlapping loadFile calls via next_prev_aux()
		this.eventsok = false;
		this.first = true;//true if it's the first file since it opened 
		
		this.intObj = null;
		
		this.formtags = null;
	//	this.prepareGalleries();
	 	
	 	this.initMilkbox();
		this.saveOptions();//then use restoreOptions()
	},//end init
	
	initMilkbox:function(){
  
		this.prepareHTML();
		this.prepareEffects();
		this.prepareEvents();
		
		this.formtags = $$('select','textarea');
		this.activated = true;
	},
	/* ****** SHOW/HIDE ****** */
	//runs only 1 time per gallery
	openTextMilkbox:function(id){

		this.closed = false;
		
		if(this.formtags.length != 0){ this.formtags.setStyle('display','none') };

		//this.overlay.setStyles({ 'top': -$(window).getScroll().y,'height':$(window).getScrollSize().y+$(window).getScroll().y });
		
			if(Browser.Engine.webkit){//fixd webkit browse
				this.overlay.setStyles({'height':document.body.scrollHeight+$(window).getScroll().y, 'top': -$(window).getScroll().y });
			}else{
				this.overlay.setStyles({'height':$(window).getScrollSize().y+$(window).getScroll().y, 'top': -$(window).getScroll().y });
			}
		
		this.center.setStyle('top',$(window).getScroll().y+this.options.topPosition);

	 
		this.overlay.tween('opacity',this.options.overlayOpacity);//onComplete: center.tween opacity
		 
		this.loadText(id)
	},
	
	loadText:function(id){
		var request	=	new Request();
		var reURL	=	"/portfolio/portfolio_data.php?action=ProfileDetailsCommentJSON&pid="+id;
		var request = new Request.JSON({
					url:reURL,
					onComplete: function(jsonObj) {
							//alert(jsonObj);
							this.setTextBox(jsonObj);							
							this.showBoxSize();
							
					}.bindWithEvent(this)
				}).send();				
	},	
	/*//runs only 1 time per gallery
	 
	*/ 
	showBoxSize:function(){
 		
 		if(this.closed){ return; };//if you close the Milkbox and an onload event is still running
 		
		this.busy == false;
 		var fileSize = new Hash();
 		var targetSize = {};
 		var b = null;
 		var p = null;
 		if(this.options.canvasBorderWidth.toInt() != 0 && this.canvas.getStyle('borderWidth').toInt() == 0){
 			b = this.options.canvasBorderWidth + ' solid ' + this.options.canvasBorderColor;
 			this.canvas.setStyle('border',b);
 		}
 		
 		if(this.options.canvasPadding.toInt() != 0 && this.canvas.getStyle('padding').toInt() == 0){
 			p = this.options.canvasPadding;
 			this.canvas.setStyle('padding',p);
 		}
 		
 		var canvasSize = this.canvas.getSize();
 		var canvasAddSize = this.canvas.getStyle('borderWidth').toInt()*2 + this.canvas.getStyle('padding').toInt()*2;
 		this.canvas.setStyles({'opacity':0, 'width':'', 'height':''});
 		
 		fileSize.extend({ 'height':400, 'width':500 });

 		var centerSize = new Hash(this.center.getStyles('width','height')).map(function(item, index){ return item.toInt(); });
		//this.canvas
 		if(fileSize.width != centerSize.width){ 
 			targetSize.width = fileSize.width + canvasAddSize;
 			targetSize.marginLeft = -(targetSize.width/2).round();
 		}
 		 		
 		var gap = (canvasSize.y-canvasAddSize > 0) ? centerSize.height - canvasSize.y : 0; 
		 
 	   targetSize.height = fileSize.height;
 	  
		//so nav doesn't move when you click next/prev
		 this.canvas.setStyles({'width':fileSize.width});

 		this.center.removeClass('mbLoading');
 		
 		var d = 0;
 		if(this.first){ d = 500; this.first = false; }
		//alert(targetSize);
		
 		(function(){ this.center.morph(targetSize); }).delay(d,this)//onComplete: show all items
	},
	
	showFile:function(file){
 		
 		if(this.closed){ return; };//if you close the Milkbox and an onload event is still running
 		
 		var fileSize = new Hash();
 		var targetSize = {};
 		var b = null;
 		var p = null;
 		if(this.options.canvasBorderWidth.toInt() != 0 && this.canvas.getStyle('borderWidth').toInt() == 0){
 			b = this.options.canvasBorderWidth + ' solid ' + this.options.canvasBorderColor;
 			this.canvas.setStyle('border',b);
 		}
 		
 		if(this.options.canvasPadding.toInt() != 0 && this.canvas.getStyle('padding').toInt() == 0){
 			p = this.options.canvasPadding;
 			this.canvas.setStyle('padding',p);
 		}
 		
 		var canvasSize = this.canvas.getSize();
 		var canvasAddSize = this.canvas.getStyle('borderWidth').toInt()*2 + this.canvas.getStyle('padding').toInt()*2;
 		this.canvas.setStyles({'opacity':0, 'width':'', 'height':''});
 		
 		if(!file.retrieve('width')){//is an image file
 			fileSize = fileSize.extend(file.getProperties('width','height')).map(function(item, index){ return item.toInt(); });
 		} else {//is an swf file
 			fileSize.extend({ 'height':file.retrieve('height').toInt(), 'width':file.retrieve('width').toInt() });
 		}

 		var centerSize = new Hash(this.center.getStyles('width','height')).map(function(item, index){ return item.toInt(); });

 		if(fileSize.width != centerSize.width){ 
 			targetSize.width = fileSize.width + canvasAddSize;
 			targetSize.marginLeft = -(targetSize.width/2).round();
 		}
 		 		
 		var gap = (canvasSize.y-canvasAddSize > 0) ? centerSize.height - canvasSize.y : 0; 

 	   targetSize.height = fileSize.height + canvasAddSize + gap;
 	   
		//so nav doesn't move when you click next/prev
		this.canvas.setStyles({'width':fileSize.width, 'height':fileSize.height});

 		this.center.removeClass('mbLoading');
 		
 		var d = 0;
 		if(this.first){ d = 500; this.first = false; }
 		(function(){ this.center.morph(targetSize); }).delay(d,this)//onComplete: show all items
	},

	showClientComment:function(opt){
		if(!opt || !opt.id){ return; }
		var fileIndex = ($chk(opt.index)) ? opt.index : 0;
		//var g = this.getGallery(opt.gallery);
		var d;
		var auto = false;
 
		this.openTextMilkbox(opt.id,fileIndex);
	},
 
	
	
	/* ****** UTILS ****** */
	
	checkFileType:function(file,type){
		var href = null;
		if($type(file) != 'string'){ href = file.retrieve('href'); } 
		else{ href = file; }
		var regexp = new RegExp("\.("+type+")$","i");
		return href.split('?')[0].test(regexp);
	},
 
	
	setFileProps:function(fileObj,propString){
		var s = propString.split(',');
		s.each(function(p,i){
			var clean = p.trim().split(':');
			fileObj.store(clean[0].trim(),clean[1].trim())
		},this);
	},
	
	changeOptions:function(obj){
		if(!obj){ return; }
		this.setOptions(obj);
 		this.center.get('morph').setOptions({ transition:this.options.resizeTransition,  duration:this.options.resizeDuration });
	},
	
	saveOptions:function(obj){
		if($chk(obj)){
			this.fullOptionsBkup = obj;
		} else {
			this.fullOptionsBkup = this.options;
		}
	},
	
	restoreOptions:function(){
		this.setOptions(this.fullOptionsBkup);
 		b = this.options.canvasBorderWidth + ' solid ' + this.options.canvasBorderColor;
 		this.canvas.setStyles({ 'border':b, 'padding':this.options.canvasPadding});
 		this.center.get('morph').setOptions({ transition:this.options.resizeTransition,  duration:this.options.resizeDuration });
	},
	
 
  
	/* ****** INIT/CLOSE ****** */
	
	//all the main events
	prepareEvents:function(xml){
	
		//galleries
		this.galleries.each(function(gallery){
		
			$$(gallery).addEvent('click',function(e){
				var button=($(e.target).match('a')) ? $(e.target) : $(e.target).getParent('a');
				e.preventDefault();			
				//this.openTextMilkbox(gallery); 
			}.bindWithEvent(this));
			
		},this);
		
		//next, prev, see next_prev_aux()
	 

		//keyboard next/prev/close
		$(window.document).addEvent('keydown',function(e){
			if(this.mode != 'fileGallery' || this.busy == true){ return; }
			if(e.key == 'right' || e.key == 'space'){ this.next_prev_aux(e,'next'); }
			else if(e.key == 'left'){ this.next_prev_aux(e,'prev'); }
			else if(e.key == 'esc'){ this.closeMilkbox(); }
		}.bindWithEvent(this));
 
		//overlay
		this.overlay.get('tween').addEvent('onComplete',function(){
			if(this.overlay.getStyle('opacity') == this.options.overlayOpacity){ 
				this.center.tween('opacity',1);
			} else if(this.overlay.getStyle('opacity') == 0) {
				this.overlay.setStyles({'height':0,'top':''});
			};
		}.bindWithEvent(this));
		
		//center
		this.center.get('morph').addEvent('onComplete',function(){
			 
			// alert($type(this.currentFile));
		 
			 this.canvas.tween('opacity',1);
			 	 
		 
	  	
			  var currentCenterHeight2 = this.inner1.getStyle('height').toInt()+5;
	 		 var currentCenterHeight = this.canvas.getStyle('height').toInt()+5;
			 var currentCenterHeight3	=	currentCenterHeight
		 
			  if(currentCenterHeight2.toInt()>currentCenterHeight.toInt()){
				  currentCenterHeight=currentCenterHeight2+20;
				 
			  }
	 
			var targetOffset = 0;
			if( currentCenterHeight > this.canvas.getSize().y ){
				targetOffset	=	this.canvas.getSize().y-currentCenterHeight
			}else{
				targetOffset	=	0;
			}
			//alert(this.canvas.getSize().y);
			 if(currentCenterHeight2.toInt()>currentCenterHeight3.toInt()){
				 targetOffset	=Math.abs(targetOffset.toInt()/2);
		
			 }
			
		
			 this.center.retrieve('setFinalHeight').start(currentCenterHeight,currentCenterHeight.toInt()+targetOffset.toInt());
			 /**/
		}.bindWithEvent(this));
		
		this.center.retrieve('setFinalHeight').addEvent('onComplete',function(){
		 
			//reset overlay height based on position and height
			var scrollSize = $(window).getScrollSize().y;
			var scrollTop = $(window).getScroll().y;
		  // alert( scrollSize +"   "+scrollTop );
			if(Browser.Engine.webkit){//fixd webkit browse
				this.overlay.setStyles({'height':document.body.scrollHeight+scrollTop, 'top':-scrollTop });
			}else{
				this.overlay.setStyles({'height':scrollSize+scrollTop, 'top':-scrollTop });
			}
			this.busy = false;
		}.bindWithEvent(this));
		
		//reset overlay height and position onResize
		window.addEvent('resize',function(){
			if(this.overlay.getStyle('opacity') == 0){ return; };//resize only if visible
			var scrollSize = $(window).getScrollSize().y;
			var scrollTop = $(window).getScroll().y;
			this.overlay.setStyles({ 'height':scrollSize+scrollTop,'top':-scrollTop });
		}.bindWithEvent(this));

		//close
		$$(this.overlay,this.close).addEvent('click',function(){ this.closeMilkbox(); }.bindWithEvent(this));
		
		//check
		this.eventsok = true;
	},
	
	next_prev_aux:function(e,direction){
		
		if(e){ 
			e.preventDefault();
			this.stopAutoPlay();
		} else { 
			//if there's no event obj, than this is called by autoPlay()
			if(this.busy || !this.fileReady){ return; }//stop autoplay()
		}

		this.busy = true; //for keyboard and autoplay
		
		var backupIndex = this.currentIndex;
		
		if(direction == "next"){
			var i= (this.currentIndex != this.currentGallery.length-1) ? this.currentIndex += 1 : this.currentIndex = 0;
			var _i= (this.currentIndex != this.currentGallery.length-1) ? this.currentIndex + 1 : 0;
		} else {
			var i= (this.currentIndex != 0) ? this.currentIndex -= 1 : this.currentIndex = this.currentGallery.length-1;
			var _i= (this.currentIndex != 0) ? this.currentIndex - 1 : this.currentGallery.length-1;		
		};
		
		this.canvas.empty();
		this.description.empty();
		this.count.empty();

		this.loadFile(this.currentGallery[i],[this.currentGallery[_i]]);
	},
	
	prepareEffects:function(){
		this.overlay.set('tween',{ duration:'short',link:'cancel' });
		this.center.set('tween',{ duration:'short',link:'chain' });
		this.center.set('morph',{ duration:this.options.resizeDuration,link:'chain',transition:this.options.resizeTransition });
		this.center.store('setFinalHeight',new Fx.Tween(this.center,{property:'height',duration:'short'}));
		this.canvas.set('tween',{ link:'chain' });
	},
	
 
		
 
	setTextBox:function(json){
		this.CaseTitle	=	json.title;
		this.CaseURL	=	json.url;
		this.CaseID		=	json.id;
		this.CaseComment	=	json.comments;
		this.CasePublisher	=	(json.publisher!=null)?json.publisher:"";
		this.CaseTechnologies	=	json.technologies;
		this.innerContentTitle.innerHTML	=	this.CaseTitle;
		this.innerContentBody.innerHTML	=	this.CaseComment;
		var urls	=	this.CaseURL.toLowerCase();
		var urls2 = urls.replace('http://',"");
		 urls2 = urls2.replace('/',"");
			//var urlitem	=	 new Element('a',{ href:urls,html:urls2 });
		
		this.innerContentFooter.innerHTML	=	this.CasePublisher+" "+urls;
		
		

		
	},
	
	prepareHTML:function(){
		
		this.overlay = new Element('div', { 'id':'mbOverlay','styles':{ 'opacity':0,'visibility':'visible','height':0,'overflow':'hidden' }}).inject($(document.body));
	
		this.center = new Element('div', {'id':'mbCenter', 'styles':{'width':this.options.initialWidth,'height':this.options.initialHeight,'marginLeft':-(this.options.initialWidth/2),'opacity':0 }}).inject($(document.body));
	 
		this.canvas = new Element('div', {'class':'client_test'}).inject(this.center);
		
		this.inner1				=	new Element('div', {'class':'client_test_pd'}).inject(this.canvas);
		this.innerNav			=	new Element('div', {'class':'client_test_Colse'}).inject(this.inner1);
		this.close			=	new Element('img',{'src':'../images/button_close.jpg','align':'right','class':'buttonimages'}).inject(this.innerNav);
		this.innerContent		=	new Element('div', {'class':'client_content'}).inject(this.innerNav,'after');
	
		this.innerContentTitle	=	new Element('div', {'class':'client_f_pd f_client_test'}).inject(this.innerContent,'after');
		this.innerContentBody	=	new Element('div', {'class':'client_f_pd client_bg'}).inject(this.innerContentTitle,'after');	
		this.innerContentFooter	=	new Element('div', {'class':'client_f_pd f_client_test1'}).inject(this.innerContentBody,'after');		
		
		this.ClearFix	=	new Element('div', {'class':'clearboth'}).inject(this.inner1,'after');
 
	},
	
	closeMilkbox:function(){
		this.cancelAllEffects();
		//this.stopAutoPlay();
		//this.setOptions(this.autoPlayBkup);

		this.currentFile = null;
		this.currentIndex = null;
		this.currentGallery = null;
 		
		 
		var border = this.center.getStyle('border-right-width').toInt();
	 
		
  	 	this.canvas.setStyles({'opacity':0 });
 	 	 
		if(this.formtags.length != 0){ this.formtags.setStyle('display','') };
		this.center.setStyles({'opacity':0,'width':this.options.initialWidth,'height':this.options.initialHeight,'marginLeft':-(this.options.initialWidth/2)});
		this.overlay.tween('opacity',0);//see onComplete in prepareEvents() 
		
	//	if(this.formtags.length != 0){ this.formtags.setStyle('display','') };
		
		this.mode = null;
		this.closed = true;
		this.first = true;
		this.fireEvent('closed');
	},
	
	/*Create Lists*/
	createList:function(jsonObj){
		
				var PorfolioMain	=	$(this.options.PorfolioMain)	;
			//	alert(this.PorfolioMain);
				PorfolioMain.empty();		
		
				var el 					= 	new  Element('div', {'class': 'preview'});
				var pf_div 				= 	new  Element('div', {'class'	: 'img_profolio'}).inject(el);				
					
				var pf_bigImages			=	new  Element('img',{'src':jsonObj.BigPic,'alt':jsonObj.title}).inject(pf_div)
				
				var pf_title			=	new  Element('div', {'html':jsonObj.title,'class'		: 'tPorfolio'}).inject(pf_div, 'after');
				var pf_button			=	new  Element('div', {'class'	: 'button_website'}).inject(pf_title, 'after');
					/*link case*/					
					 var pf_button_a				=	new  Element('a',{'href':jsonObj.url,"target":"_blank"}).inject(pf_button);
					 var pf_button_Images		=	new  Element('img',{'src':'../images/button_website.jpg','alt':jsonObj.title}).inject(pf_button_a);
					 var pf_button_b				=	new  Element('a',{'id':"ReadClientTestimonial",'name':'Items_'+jsonObj.id}).inject(pf_button_a, 'after');
					 var pf_button_Imagesb		=new  Element('img',{'src':'../images/button_read_client.jpg','class':'buttonimages','alt':jsonObj.title}).inject(pf_button_b);
					 
				var pf_desction			=	new  Element('p',{'html':jsonObj.desction}).inject(pf_button, 'after');
				var pf_technologies		=	new  Element('div', {'class'	: 'f_bold line',	'html':'Technologies used'}).inject(pf_desction, 'after');
				var pf_technologiesList	=	new  Element('ul', {'class'		: 'technologies'}).inject(pf_technologies, 'after');
				
				var tech_str			=	jsonObj.tech;
				var tech_arr	=	tech_str.split(",");
			 
				if(tech_arr.length>0){			
					tech_arr.each(function(tech) {									
									var pf_technologiesItem		=	new  Element('li',{'html':tech}).inject(pf_technologiesList);									
					 });					
				}				
				el.inject(PorfolioMain);				
				 if(jsonObj.comments=="false"){
					 pf_button_b.setStyles({"display":"none"});
				 }				
		 		pf_button_b.addEvent('click', function(e){																		
						e.preventDefault();
						var button=($(e.target).match('a')) ? $(e.target) : $(e.target).getParent('a');
						var ids	=button.name.replace(new RegExp("Items_"), "");											
						this.showClientComment({ id:ids });
				}.bindWithEvent(this)
				
				)		
	},
	caseLinks:function(id){
			 
				var reURL	=	'/portfolio/portfolio_data.php?action=PorfolioDetailsJSON&pid='+id;
		 
				var request = new Request.JSON({
					url:reURL,
					onComplete: function(jsonObj) {
						this.createList(jsonObj);
					}.bindWithEvent(this)
				}	
				).send();
		
		},
	
	
	
	cancelAllEffects:function(){
		this.overlay.get('tween').cancel();
		this.center.get('morph').cancel();
		this.center.get('tween').cancel();
		this.center.retrieve('setFinalHeight').cancel();
		this.canvas.get('tween').cancel();
	}
	
});//END MILKBOX;

 
