// var tonyPopup = new TonyPopup();

function TonyPopup(bID){
	
	this.bID=bID;
	
	this.wipeOpacity=.9;
	
	this.editBarHeight=0;
	
	this.rules=[];
	
	this.init = function(){ 
		if(this.initiated) return;
		this.servicesURL=$('#tonyPopup_servicesURL').val();
		this.rootURL=$('#tonyPopup_rootURL').val();
		var ccmEditBar=$('#ccm-page-controls');  
		if( ccmEditBar && ccmEditBar.get(0) ){
			this.editBarHeight=ccmEditBar.height();  
		} 
		this.addPopupHTML();
		this.activateLinks(); 
		this.initiated=1;
	}
	
	this.addPopupHTML = function(){
		var b=$('body'); 
		var footerHTML='<div id="TonyPopup_wrap'+this.bID+'" class="TonyPopup_wrap"><div class="TonyPopup_pageWipe"></div><div class="TonyPopup_throbber"></div><div class="TonyPopup_box"><div class="TonyPopup_boxBodyWrap"><div class="TonyPopup_boxBody"></div></div><div class="TonyPopup_boxFooter"></div></div></div>';
		b.prepend(footerHTML);
		
		this.popupWrap= $('#TonyPopup_wrap'+this.bID);
		this.pw= this.popupWrap.find('.TonyPopup_pageWipe'); 
		this.popupThrobber = this.popupWrap.find('.TonyPopup_throbber'); 
		this.pageWipeBox = this.popupWrap.find('.TonyPopup_box'); 
		
		this.pw.get(0).tonyPopup=this;
		this.pw.click( function(){ this.tonyPopup.modalClose(); } );
	}
	
	this.invalidSelectorRuleMsg='Invalid Popup Selector Rule: ';
	this.basePath='';
	//this is run during startup, and after each time the popup loads (with limited scope)
	this.activateLinks = function(popupLinksOnly){
		
		var tonyPopup=this;
		var pathRules=[];
		var rule;
		var els=[];
		var selectorStr='';
		
		for(var i=0; i<this.rules.length ;i++){
			
			rule=this.rules[i];
			els=[]; 
			
			if( rule.type == 'class' ){  
			
				selectorStr='a.'+( rule.val.replace(/[^a-zA-Z 0-9]+/gi,'') );
				if(popupLinksOnly) els = this.pageWipeBox.find( selectorStr );
				else els = $( selectorStr );
				
				els.each( function(i,el){
	 				tonyPopup.addClick(el,rule);
				});
				
			}else if( rule.type == 'selector' ){  
				selectorStr=rule.val.replace(/[^a-zA-Z 0-9\#\.\ \_\- \[\]\=]+/gi,''); 
				try{
					if(popupLinksOnly) els = this.pageWipeBox.find( selectorStr );
					else els=$( selectorStr );
				}catch(e){ alert( this.invalidSelectorRuleMsg + rule.val) } 
				if(els && els.length) els.each( function(i,el){
	 				tonyPopup.addClick(el,rule);
				});				
				
			}else if( rule.type == 'path' ){ 
				pathRules.push(rule);
			}  
		}
		
		if( pathRules.length>0 ){ 
			if(popupLinksOnly) els = this.pageWipeBox.find('a');
			else els = $('a');
			els.each(function(i,el){
				for(var j=0; j<pathRules.length; j++){ 
					var url = $(el).attr('popupSRC');
					if( !url ) url=el.href; 
					url=url.replace(tonyPopup.basePath,''); 
					if( url.toLowerCase().indexOf( pathRules[j].val.toLowerCase() ) == 0 || url.toLowerCase().indexOf( ('index.php'+pathRules[j].val).toLowerCase() ) == 0 ) 
						tonyPopup.addClick( el,pathRules[j] );
				}
			})
		}
	},
	
	this.addClick = function(el,rule){
		el.tonyPopup=this;
		elObj=$(el);
		if(elObj.attr('popupLinkAdded')==1) return
		var url = elObj.attr('popupSRC');
		if( !url ) url=el.href; 		
		var isModal = (rule.isModal==1 || elObj.hasClass('popupIsModal')) ? 1 : 0;
		var showTitle = (rule.showTitle==1 || elObj.hasClass('popupShowTitle')) ? 1 : 0;
		var area = ( elObj.attr('popupArea') ) ? elObj.attr('popupArea') : rule.area; 
		elObj.click(function(){ this.tonyPopup.loadURL( url, isModal, showTitle, area ); return false;}); 
		elObj.attr('popupLinkAdded',1);
	}
	
	this.pageWipeInit = function(){
		if(!this.pw || this.hidden) return;
		try{ 
		//var pwb=$('pageWipeBottom');
		//alert( $(window).height() ); 
		//alert( $(window).scrollTop() );
		wsh=$(document).height(); 
		/* 
		if(pwb){
			pwbY=pwb.getPosition().y+pwb.getSize().y; 
			if(pwbY>wsh) this.pw.css('height',pwbY);
			else this.pw.css('height',wsh);
		}else */ this.popupWrap.css('height',wsh);
		this.popupWrap.css( 'width', $(document).width() );
		this.centerBox(); 
		}catch(e){ alert(e.message+' pageWipeInit') }
	}	
	
	this.loadURL = function ( url, isModal, showTitle, area){ 
		if(!url) return;
		this.modalCloseOn=isModal; 
		this.toggleSelects(0);
		this.showThrobber();
		/* 
		if(!noScroll) popupHelper.scrollUp();
		var a=new Ajax(url,{method:'get',update:this.pageWipeBox,evalScripts:true}).request(); //,evalScripts:true
		a.callback=callback;
		a.addEvent('onComplete',function(){
			if( typeof(this.callback)=='function' ) this.callback();
			popupHelper.contentReady();	 
			$('pageWipeBox').forceEvalScripts();
		})
		*/ 
		this.pageWipeBox.css('display','none');
		this.pageWipeBox.find('.TonyPopup_boxBody').html(''); 
		var tonyPopup=this;
		$.ajax({ 
			type:'post',					  
			data:'mode=getPage&url='+encodeURIComponent(url)+'&showTitle='+parseInt(showTitle)+'&bID='+parseInt(this.bID)+'&area='+area,
			url: this.servicesURL,
			success: function(response){ 
				//alert(response);
				eval('var jObj='+response);
				if( jObj && jObj.error ){
					tonyPopup.hide();
					alert(jObj.error);
				}else{  
					tonyPopup.pageWipeBox.find('.TonyPopup_boxBody').html( jObj.html ); 
					//alert(jObj.html);
					tonyPopup.addHeaderCSS(jObj.cssFiles);
					tonyPopup.addHeaderJS(jObj.jsFiles);
					tonyPopup.contentReady(); 
				}
			}
		}); 
	} 
	
	this.addHeaderCSS = function(headerFiles){ 
		if(typeof(headerFiles)=='undefined' || !headerFiles.length) return;
		var linkTags=$('link');
		var tonyPopup=this;
		for(var i=0;i<headerFiles.length;i++){ 
			var file=headerFiles[i];  
			var linkExists=0;
			linkTags.each(function(i,el){ if(el.href==file || el.href==(tonyPopup.rootURL+file) ) linkExists=1; });
			if(linkExists) continue;
			var l=document.createElement('link');
			//l.id='book_styles_design'+parseInt(BookDesign.designId);
			l.type='text/css';
			l.rel='stylesheet';  
			$('head').append(l);
			l.href=file; 
		}
	}

	this.addHeaderJS = function(headerFiles){ 
		if(typeof(headerFiles)=='undefined' || !headerFiles.length) return;
		var scriptTags=$('script');
		var tonyPopup=this;
		for(var i=0;i<headerFiles.length;i++){
			var file=headerFiles[i];   
			var scriptExists=0;
			scriptTags.each(function(i,el){ if( typeof(el.src)!='undefined' && el.src==file || el.src==(tonyPopup.rootURL+file) ) scriptExists=1; });
			if(scriptExists) continue; 
			/*
			var s=document.createElement('script');
			s.type='text/javascript';
			//$(s).html('alert("got here")');
			$('head').append(s);
			$(s).attr('src',file); 
			alert(file);
			*/ 
			$.ajaxSetup({async: false});
			$.getScript(file);
			$.ajaxSetup({async: true});
		}
	}
	
	this.showThrobber = function(){
		this.showPageWipe(); 
		//var t = Math.floor( ( $(window).height() / 2 ) - ( parseInt(this.popupThrobber.css('height').replace('px',''))/2+20) ) +'px';
		var t = $(window).scrollTop() + Math.floor( ($(window).height() / 2) - ( this.popupThrobber.height() / 2 ) );
		this.popupThrobber.css('top', t ) ;
		this.popupThrobber.css('display','block');
	}
	
	this.hideThrobber = function(){
		this.popupThrobber.css('display','none');
	}
	
	this.showPageWipe = function(){
		this.hidden=0;
		this.pageWipeInit();
		//if(this.popupWrap.css('display')=='block') return;
		
		//fade in main wrap
		if(this.popupWrap.css('display')!='block' || this.popupWrap.css('opacity')!=1){
			if(this.popupWrap.css('display')!='block'){
				this.popupWrap.css('opacity',0); 
				this.popupWrap.css('display','block');
			} 
			this.pw.css('opacity',this.wipeOpacity);
			this.popupWrap.animate( {'opacity': 1}, 500 ); 
		} 
		//this.popupWrap.fx.addEvent('onComplete',function(el){ popupHelper.pageWipeInit(); }); 
	}
	
	this.contentReady = function (){  
		this.hideThrobber();
		this.showBox();		
		this.activateLinks(1);
		//window.fireEvent('pageready');
		this.pageWipeInit(); 
	}	
	
	this.showBox=function(){ 
		this.popupWrap.css('display','block'); 
		this.pageWipeBox.css('display','block');
		/*
		if( this.pageWipeBox.css('opacity')==1 && this.pageWipeBox.css('display')=='block') return;
		if( this.pageWipeBox.fx && typeof(this.pageWipeBox.fx.stop)=='function') this.pageWipeBox.fx.stop();
		if(this.pageWipeBox.style.display!='block'){
			this.pageWipeBox.setStyle('opacity',0);
			this.pageWipeBox.style.display='block';
		}
		this.pageWipeBox.fx = new Fx.Style( this.pageWipeBox, 'opacity',{duration:1000,fps:20,transition:Fx.Transitions.Cubic.easeInOut}).start(1);
		*/
	}
	
	this.centerBox=function(){  
		var pwh=this.pageWipeBox.outerHeight(), wh=$(window).height(), t=30;
		if(!pwh) return; 
		
		if(pwh<wh){
			//var pwb=$E('#pageWipeBottom',this.pageWipeBox), diff=wh-pwh; 
			//if(pwb) diff=diff+pwb.getHeight();
			//t=Math.floor(diff/2);
		} 
		t=t+$(window).scrollTop()+this.editBarHeight;
		/* 
		this.pageWipeBox.tfx = new Fx.Style( this.pageWipeBox, 'top',{duration:400,fps:20,transition:Fx.Transitions.Cubic.easeIn})		
		this.pageWipeBox.tfx.addEvent('onComplete',function(){ 
			//make sure the page wipe extends past the popup
			var pwb=$('pageWipeBottom');
			var pwh=popupHelper.pw.css('height').replace(/px/i,'');
			pwbY=this.pageWipeBox.position().top+pwb.getSize().y; 
			if(pwh<pwbY) this.pw.css('height',(pwbY+40));
		}) 
		*/ 
		if( this.pageWipeBox.css('top').replace('px','')!=t){
			this.pageWipeBox.css('top',t); 
		} 
		//make sure that pageWipe doesn't need to be longer, if box now extends past bottom
		var boxBottom=this.pageWipeBox.position().top+this.pageWipeBox.outerHeight(); 
		if( boxBottom>=this.popupWrap.height() ){ 
			this.popupWrap.height(boxBottom+40); 
		}
	},	
	
	this.hidden=1;
	this.hide = function(){ 
		this.popupWrap.animate( {'opacity':0},500,function(){ $(this).css('display','none');  $(this).find('.TonyPopup_boxBody').html(''); });
		/* 
		if( this.pw.fx && typeof(this.pw.fx.stop)=='function') this.pw.fx.stop();
		this.pw.fx = new Fx.Style( this.pw, 'opacity',{duration:1000,fps:20,transition:Fx.Transitions.Cubic.easeInOut}).start(0);
		this.pw.fx.addEvent('onComplete',function(el){ popupHelper.popupWrap.style.display='none'; this.toggleSelects(1); window.fireEvent('hidePopupWipe'); });		
		*/
		this.hidden=1;
	}
	
	//for IE z-index bug
	this.toggleSelects = function(display){
	  for (j=0; j<document.forms.length; j++)
		  for (i=0; i<document.forms[j].elements.length; i++) {
			 n=document.forms[j].elements[i];
			 if (n.tagName == "SELECT"){
				if(display==1) n.style.display='inline';
				else n.style.display='none';
			 }
		  }
	}	
	
	this.modalCloseOn=0;
	this.modalClose=function(){ if(this.modalCloseOn) this.hide();  }
}

