
function ProPhoto(bID){ 

	this.bID=parseInt(bID);
	
	this.mainImgPadding=12;
	
	this.init=function(){
		
		this.mainWrap=$('#proPhotoWrap'+this.bID);  
		if( !this.mainWrap.html() ) return false;
		
		//has this instanced already been initialized 
		this.initializedEl=this.mainWrap.find('#proPhoto_initialized');
		if(this.initializedEl.val()==1) return false; 
		this.initializedEl.val(1);
		
		this.viewImgEventName=this.mainWrap.find('#proPhoto_viewImgEventName').val();
		this.tagsCID=parseInt(this.mainWrap.find('#proPhoto_tagsCID').val());
		this.linkCID=parseInt(this.mainWrap.find('#proPhoto_linkCID').val());
		this.mw=parseInt(this.mainWrap.find('#proPhoto_mw').val());
		this.mh=parseInt(this.mainWrap.find('#proPhoto_mh').val());
		this.dp=parseInt(this.mainWrap.find('#proPhoto_dp').val());
		this.attrs=this.mainWrap.find('#proPhoto_attrs').val();
		this.fixedHeight=parseInt(this.mainWrap.find('#proPhoto_fixedHeight').val());
		this.enlargeMode=this.mainWrap.find('#proPhoto_enlargeMode').val();
		
		this.servicesURL=$('#proPhoto_servicesURL').val();
		this.mainImg=this.mainWrap.find('.mainImage');
		this.mainImageTarget=this.mainWrap.find('.mainImageTarget');
		var pc=$('div#ccm-page-controls')
		this.scrollOffset=(pc && pc.html())?parseInt(pc.css('height').replace('px',''))+24:24; 
		this.currentFID=$('#proPhotoCurrentFID'+this.bID).val();
		if(this.mainImageTarget && this.mainImageTarget.html()) this.mainImgExists=1;
		var bID=this.bID;
		var proPhotoInstance=this; 
		this.mainWrap.find('.pagination a').each(function(){ this.href=this.href+"#proPhoto"+bID;  });
		
		var ArrowR=this.mainImg.find('.arrowRight');
		if(ArrowR && ArrowR.get(0)){
			ArrowR.get(0).proPhotoInstance=this; 
			ArrowR.click(function(){ try{ this.proPhotoInstance.next(); }catch(e){ alert('error: '+e.message)  } return false; });
			var ArrowL=this.mainImg.find('.arrowLeft');
			ArrowL.get(0).proPhotoInstance=this; 
			ArrowL.click(function(){ try{ this.proPhotoInstance.previous(); }catch(e){ alert('error: '+e.message) }  return false;  });
		}
		
		
		this.fIDs=[];
		var fIDsTemp=this.fIDs;
		this.mainWrap.find('.proPhotoImgWrap').each(function(){ 
			var fID=this.id.replace('proPhotoImgWrap'+bID+'_',''); 
			fIDsTemp.push({ fID:fID })											 			
		});	
		
		this.setMainSize(); 
		
		//handle resize  
		if( typeof(window.proPhotoObjs)=='undefined' ){
			window.proPhotoObjs=[]; 
			$(window).resize( function(){ for(var i=0; i < this.proPhotoObjs.length ;i++) this.proPhotoObjs[i].resize();  });
		}
		window.proPhotoObjs.push(this);
		
		this.filmStrip=this.mainWrap.find('.proPhotoFilmStrip'); 
		this.filmStripW = this.filmStrip.width(); 
		this.filmStripInner=this.mainWrap.find('.proPhotoFilmStripInner');
		
		this.sliderDiv = this.mainWrap.find('.proPhotoFilmStrip-slider'); 
		
		if( this.enlargeMode!='link' && this.enlargeMode!='none' ){ 
			this.mainWrap.find('.proPhotoThumbLink').live('click',function(e){
				var fID = parseInt(this.id.replace('proPhotoThumbFID_',''));
				proPhotoInstance.showLarge(fID,this);
				return false;
			}); 
		}

		this.enableKeyPressEvents();
		
		if( this.filmStrip.html() ){
		
			this.sliderDiv.get(0).proPhotoInstance=this; 
			
			if( this.sliderDiv && typeof(this.sliderDiv.slider)=='function' )
				this.sliderObj = this.sliderDiv.slider( { 
				step: 1, 
				animate: true,
				slide: function(e, ui) {  
					var maxScroll = this.proPhotoInstance.filmStripInner.width() - this.proPhotoInstance.filmStripW - 8; 
					this.proPhotoInstance.filmStripInner.css( 'left' , ui.value * maxScroll / -100 );  
				}
			} );
			this.filmStrip.css('overflow-x','hidden');  
			this.filmStrip.css('overflow','hidden'); 
			this.sliderDiv.css('display',this.filmStrip.css('display'));
			
			
			if( this.filmStripInner ){
				
				setTimeout( function(){ proPhotoInstance.centerStripDelayed=1; }, 2000);
				var proPhoto=this;
				
				this.filmStripInner.find('img').each(function(i,el){ 
					el.proPhoto=proPhoto;										  
					el.onload=function(){ 
						if(this.proPhoto.photosLoaderTmr) clearTimeout(this.proPhoto.photosLoadedTmr);
						this.proPhoto.centerShortImageStrip();
						this.proPhoto.photosLoadedTmr=setTimeout( function(){ proPhotoInstance.centerShortImageStrip(); },1000);
					}
					proPhoto.photosLoadedTmr=setTimeout( function(){ proPhotoInstance.centerShortImageStrip(); },1000);
					$(el).mousedown(function(e){
						if( e.preventDefault) e.preventDefault();
					});
					
				}) 
			}
			
			//this.enableFilmstripDrag(); 
		
		}
	},
	
	this.setMainSize=function(){
		var mainImg = this.mainImageTarget.find('img');
		if(!mainImg.length) return; 
		var imgH = parseInt( mainImg.height() );
		var imgW = parseInt( mainImg.width() );
		if(!imgH || !imgW) {
			var q = mainImg.get(0).className.split(' ');	
			for(var i=0;i<q.length;i++){
				if(q[i].indexOf('width')>-1) 
					imgW=parseInt(q[i].replace('width',''));
				if(q[i].indexOf('height')>-1) 
					imgH=parseInt(q[i].replace('height',''));
			}
		}
		this.mainImageTarget.animate( { height: (imgH+this.mainImgPadding) },100 ); 
		var innerWidth= imgW + this.mainImgPadding;  
		this.mainImg.find('.mainImgDataWrap').animate( {width:innerWidth}, 100, "linear", function(){ } );
	},
	
	this.enableKeyPressEvents=function(){ 
		var proPhotoInstance=this;
		$(document).keydown(function(e) {
			if(e.keyCode==37) proPhotoInstance.previous();
			else if(e.keyCode==39) proPhotoInstance.next();
		});	
	
	},
	
	this.enableFilmstripDrag=function(){

		var mainImage=$('.mainImage');
		var filmStripInner = this.filmStripInner;
		var filmStrip = this.filmStrip;
		ProPhotoGlobal.speedXCum=0;
		var proPhotoInstance=this;
		
		var $doc=$(document);
		$doc.mousemove(function (e) {
			ProPhotoGlobal.mouseX = e.clientX;
		});
		
		$doc.mousedown(function(e){
			
			ProPhotoGlobal.startMouseX=ProPhotoGlobal.mouseX;	
			if( e.target.nodeName.toLowerCase()!='img' || 
				e.target.className.indexOf('proPhotoThumb') == -1 ) 
					return; 
				 				
			ProPhotoGlobal.filmStripDragging=1;
			
			ProPhotoGlobal.filmStripInnerW = proPhotoInstance.filmStripInner.width();
			
			ProPhotoGlobal.maxLeftPost = ( filmStripInner.width() - filmStrip.width() ) * -1;

		});
		
		$doc.mouseup(function(){
			ProPhotoGlobal.filmStripDragging=0;
		});
		
		var filmStripInterval=setInterval(function(){
												   
			if(!ProPhotoGlobal.prevMouseX)
				ProPhotoGlobal.prevMouseX=ProPhotoGlobal.mouseX; 
			
			if( ProPhotoGlobal.filmStripDragging || (ProPhotoGlobal.speedX>.5 || ProPhotoGlobal.speedX<-.5 ) ){  
			
				var d=0, l = filmStripInner.position().left; 
				
				if(ProPhotoGlobal.filmStripDragging){
					d = ProPhotoGlobal.mouseX - ProPhotoGlobal.prevMouseX;
					
					ProPhotoGlobal.speedX=(ProPhotoGlobal.speedX+d)/2;
				}else{
					
					ProPhotoGlobal.speedX*=.88;
					
					d = ProPhotoGlobal.speedX; 
					
				}
				
				var newL = (l+d);
				if( newL > 0 ) newL=0;
				else if( newL < ProPhotoGlobal.maxLeftPost ) newL=ProPhotoGlobal.maxLeftPost;
				
				filmStripInner.css( 'left', newL );	
				
				//
				var sliderL = newL / (ProPhotoGlobal.filmStripInnerW-proPhotoInstance.filmStripW) * -100;
				proPhotoInstance.sliderDiv.find('a').css( 'left', sliderL+'%' );
				
			}
			
			ProPhotoGlobal.prevMouseX = ProPhotoGlobal.mouseX; 
			
		},50);
		
	},
	
	this.resize=function(){ 
		this.filmStripW = this.filmStrip.width(); 
	},
	
	//center filmstrip & hide scroller if smaller than area width, run after all images loaded
	this.centerShortImageStrip=function(){
		if(this.photosLoaderTmr) clearTimeout(this.photosLoadedTmr);
		
		var proPhotoInstance=this;
		if(!this.centerStripDelayed)  this.photosLoadedTmr=setTimeout( function(){ proPhotoInstance.centerShortImageStrip(); },1000);
		else this.photosLoadedTmr=setTimeout( function(){ proPhotoInstance.centerShortImageStrip(); },5000);
		
		this.filmStripW = this.filmStrip.width(); 
		
		if( this.filmStripW > this.filmStripInner.width() ){ 
			this.sliderDiv.css('display','none');
			var leftPos=Math.round((this.filmStripW-this.filmStripInner.width())/2);
			this.filmStripInner.animate( { left:leftPos }, 400 ); 
			this.sliderHidden=1;
		}else if(this.sliderHidden){
			this.sliderDiv.css('display','block');
			this.filmStripInner.animate( { left:0 },400 );
			this.sliderHidden=0;
		}
	}
	
	this.next=function(){
		var pos=0;
		for(var i=0;i<this.fIDs.length;i++){
			if( this.fIDs[i].fID==this.currentFID ){
				pos=i;
				break;	
			}
		}
		if((pos+1)>=this.fIDs.length) this.loadLargeImg(this.fIDs[0].fID);
		else this.loadLargeImg(this.fIDs[pos+1].fID);
		return false;
	}
	
	this.previous=function(){  
		var pos=0; 
		for(var i=0;i<this.fIDs.length;i++){
			if( this.fIDs[i].fID==this.currentFID ){
				pos=i;
				break;	
			}
		}
		if((pos-1)<0) this.loadLargeImg(this.fIDs[this.fIDs.length-1].fID);
		else this.loadLargeImg(this.fIDs[pos-1].fID);
		return false;
	}
	
	this.showLarge=function(fID,a){ 
	
		//disable click if image dragged
		if( Math.abs(ProPhotoGlobal.startMouseX - ProPhotoGlobal.mouseX) >10 ) return false;
		
		if(!this.mainImgExists) return true;
		if(a) a.blur(); 
		this.loadLargeImg(fID);
		return false;
	}
	
	this.tagsCID=0;
	this.linkCID=0;
	this.viewImgEventName="View Filmstrip Image:";
	this.loadLargeImg=function(fID){  
		
		this.currentFID=fID; 
		this.mainWrap.find('.proPhotoImgWrap').removeClass('selected');
		var currentImg=this.mainWrap.find('#proPhotoImgWrap'+this.bID+'_'+fID)
		currentImg.addClass('selected') 
		this.scrollFilmStrip(fID);
		try{ if(this.loadPhotoAjax) this.loadPhotoAjax.abort(); }catch(e){} //suppress jquery/firefox bug, resolved in jquery 1.4.1
		this.pendingURL=currentImg.find('a').attr('href'); 
		if( !parseInt(this.bID) && this.proPhotoInstance) var ProPhotoInstance=this.proPhotoInstance;
		else var ProPhotoInstance = this; 
		
		ProPhotoInstance.req = this.mainImageTarget.animate( {opacity:.0}, 300, "linear" );
		this.loadPhotoAjax=$.ajax({ 
			url: this.servicesURL+'?mode=largeImg&fID='+fID+'&bID='+this.bID+'&tagsCID='+this.tagsCID+'&linkCID='+this.linkCID+'&mw='+this.mw+'&mh='+this.mh+'&attr='+this.attr+'&dp='+this.dp,  
			success: function(response){ 
				eval('var jObj='+response); 
				if(jObj.error){ 
				}else{   
					var animateOpts = {opacity:.0}
					if( !ProPhotoInstance.fixedHeight ) animateOpts.height = jObj.imgH+ProPhotoInstance.mainImgPadding;
					try{
						if(ProPhotoInstance.req && typeof(ProPhotoInstance.req.abort)=='function')
							ProPhotoInstance.req.abort();
					}catch(e){ }
					ProPhotoInstance.mainImageTarget.animate( animateOpts, 300, "linear", 
						function(){ 
							ProPhotoInstance.mainImageTarget.get(0).innerHTML=jObj.html;
							ProPhotoInstance.mainImg.find('.imgTitle').html(jObj.title)
							//ProPhotoInstance.mainImg.find('.tagLinks').html(jObj.tagLinks)
							ProPhotoInstance.mainImg.find('.proPhoto_imgDetails').html(jObj.details_html)
							//ProPhotoInstance.mainImg.find('.imgOpts a').get(0).href='/photo/?fID='+fID; 
							if(ProPhotoInstance.pendingURL){
								var detailsA=ProPhotoInstance.mainImg.find('.imgOpts a')
								if(detailsA && detailsA.get(0)) detailsA.get(0).href=ProPhotoInstance.pendingURL;
							}
							
							var innerWidth=parseInt(jObj.imgW)+parseInt(ProPhotoInstance.mainImgPadding); 
					
							ProPhotoInstance.mainImageTarget.animate({opacity:1},500);
							ProPhotoInstance.mainImg.find('.mainImgDataWrap').animate({width:innerWidth},500);
							//track event on tony_stats traffic monitoring package 
							$(document).trigger('statsEvent',{'title':ProPhotoInstance.viewImgEventName,'url':null,'eventVal':jObj.title });
					});
					
				}
			}
		});
		
		return false;
	}
	
	this.scrollFilmStrip=function(fID){ 
		if(!this.filmStrip.html() || this.sliderHidden) return false; 
		
		var imgWrap=this.filmStrip.find('#proPhotoImgWrap'+this.bID+'_'+fID);  
		var filmStripInnerW = this.filmStripInner.width();  
		var leftPos = imgWrap.position().left*-1 + (this.filmStripW/2) - (imgWrap.width()/2); 
		if(leftPos>0) leftPos=0;
		if( leftPos < (filmStripInnerW-this.filmStripW)*-1 ) 
			leftPos=(filmStripInnerW-this.filmStripW)*-1; 
		
		var instance = this;  
		clearInterval(this.interval); 
		this.interval = setInterval(function(){   
			var oldL = (instance.lastFilmstripLPos) ? instance.lastFilmstripLPos : parseFloat(instance.filmStripInner.css('left').replace('px','')); 								 
			var newL = ( oldL*4 + leftPos) / 5; 
			if( (newL-leftPos)>-2 && (newL-leftPos)<2 ) newL = leftPos;  
			instance.filmStripInner.css('left',newL); 
			instance.lastFilmstripLPos = newL; 
			if(newL==leftPos){ 
				clearInterval(instance.interval);	
			}
		},50); 
		
		if( this.sliderObj && typeof(this.sliderObj.slider)=='function' )
			this.sliderObj.slider( 'value', leftPos / (filmStripInnerW-this.filmStripW-8) * -100 ); 
	}
	
}

var ProPhotoGlobal = {
	imgNum:0,
	proPhotoPreloads:[],
	startMouseX:0,
	mouseX:0,
	speedX:0,
	init:function(){ 
		this.proPhotoPreloads=$('.proPhotoPreload');
		
		if (!document.images) return;
		//detect when images are loaded 
		$.event.special.load = {
			setup: function(data, namespaces, hollaback) {
				var retVal = false;
				if (typeof(this.tagName) != "undefined" && this.tagName.toLowerCase() === 'img' && this.src !== "") {
				
					// Image is already complete, fire the hollaback (fixes browser issues were cached
					// images isn't triggering the load event)
					if (this.complete || this.readyState === 4) { 
						//if(typeof(hollaback)=='undefined' || !hollaback) hollaback=function(){ };
						$(this).bind('load', data || {}, hollaback).trigger('load');
						retVal = true;
					} 
					// Check if data URI images is supported, fire 'error' event if not
					else if (this.readyState === 'uninitialized' && this.src.indexOf('data:') >= 0) {
						$(this).trigger('error');
						retVal = true;
					} 
				} 
				return retVal;
			}
		}		
		
		this.next();
		
		this.initInstances();
	},
	
	initInstances:function(){ 
		$('div.proPhotoWrap').each(function(i,el){ 
			var bID = parseInt(el.id.replace('proPhotoWrap',''));
			try{ 
				var proPhotoInstance=new ProPhoto(bID);
				proPhotoInstance.init(); 
			}catch(e){ 
				alert(e.message);  
			}
		});
	}, 
	
	next:function(){ 
		if(this.proPhotoPreloads.length<this.imgNum+1) return; 
		var url = this.proPhotoPreloads.get(this.imgNum).innerHTML
		this.imgNum++;
		var img = new Image();
		try{
			$(img).bind('load',function(){ ProPhotoGlobal.next(); }); 
		}catch(e){
			setTimeout('ProPhotoGlobal.next()',500);
		}
		img.src =url;
	}
}
$(function(){ProPhotoGlobal.init();});


//popup block integration 
$(document).bind('popup',function(){
	ProPhotoGlobal.initInstances(); 
});

