/**
 * Dom Ready Events
 * @author Matt Pike
 * @date 2010-11-09
 */
window.addEvent('domready',function(){
	
	// Add feature sets (3 set vertical slider on section home pages)
	$$('.featureSet').each(function(fsContainer){
		var fs = new FeatureSet(fsContainer);
	});
	
	// Add animated monitors
	$$('.monitor').each(function(monContainer){
		if(!monContainer.hasClass('dontAnimate')){
			var is = new ImageTableScroller(monContainer);
		}
	});
	
	// Add image faders
	$$('.imageFader').each(function(ifContainer){
		if(ifContainer.hasClass('autoCycle')){
			var options = {'autoCycle':true};
		}else{
			var options = {'autoCycle':false};
		}
		var ifader = new ImageFader(ifContainer, options);
	});
	
	// Add hyperlink events
	$$('a').each(function(link){
		attachLinkEvents(link);
	});
	
	// Sortable Tables
	$$('table.sortable').each(function(table){
		new HtmlTable(table,{"sortable":true,"parsers":(table.get('data:parsers')).split(',')});
	});
	
	// Date Pickers
	var dateInputs = $$('input.date');
	if(dateInputs && dateInputs.length){
		new Picker.Date(dateInputs, {
		    timePicker: false,
		    positionOffset: {x: 5, y: 0},
		    pickerClass: 'datepicker',
		    useFadeInOut: true, // !Browser.ie
		  //  inputOutputFormat: '%Y-%m-%d',
		    format: '%Y-%m-%d',
		    debug:true
		});
	}
	
	// Delete Forms
	$$('form.deleteFrm').each(function(frm){
		frm.addEvent('submit',function(e){
			e.stop();
			frm.getElement('input[type=image]').set('src','/images/icons/boom.png');
			var tr = frm.getParent('tr');
			tr.addClass('toDelete');
			var cancelDelete = function(){
				frm.getElement('input[type=image]').set('src','/images/icons/bomb.png');
				tr.removeClass('toDelete');
			};
			if(confirm('Are you sure you wish to delete this?')){
				frm.set('send', {
			        noCache: true,
			        onFailure: function(){
			        	alert('Request returned error');
			        	cancelDelete();
			        },
			        onComplete: function(resp) {
			            resp = JSON.decode(resp);
			            if(resp.success){
			                tr.fade('out').get('tween').chain(function(){
			                	tr.destroy();
			                });
			            }else if(resp.err){
			                alert(resp.msg);
			                frm.getElement('input[type=image]').set('src','/images/icons/bomb.png');
							tr.removeClass('toDelete');
			            }else{
			            	alert('Sorry, there has been an error');
			            	cancelDelete();
			            }
			        }
			    }).send();
			}else{
				cancelDelete();
			}
		});
	});
});

/**
 * Full Page Load Events
 */
window.addEvent('load',function(){
	// Make sure bordered column extends to bottom
	$$('div.borderedColumn').each(function(sideCol){
		var mainCol = sideCol.getPrevious('div.sidePanelContent');
		if(mainCol){
			var mainColDim 	= mainCol.getDimensions();
			var sideColDim 	= sideCol.getDimensions();
			if(mainColDim.height > sideColDim.height){
				sideCol.setStyle('height',mainColDim.height+'px');
			}
		}
	});
	$$('.setFocus').each(function(el){
		el.focus();
	});
});

/**
 * Extend Element
 */
Element.implement({
	
	/**
	 * Add a tag to an input box
	 * @param string tag
	 */
	addTag:function(tag){
		if(!(this.get('value')+'').contains(tag,',')){
			this.set('value',(this.get('value') ? this.get('value')+','+tag : tag));
		}else{
			this.set("value",this.get("value").replace(tag,''));
			//if(this.get('value')==',') this.set('value','');
			if((this.get('value')).substr(0,1)==',') this.set('value',(this.get('value')).substr(1));
		}
		while((this.get('value')).contains(',,')){
			this.set("value",this.get("value").replace(',,',','));
		}
	}
});

/**
 * Class for handling a single lightbox and its mask
 */
var LightBox = new Class({
	
	mask : null,
	req : null,
	frame : null,
	container : null,
	// title : null,
	closeLnk : null,
	
	/**
	 * Constructor
	 * @param Element windowElement
	 * @param Element frameElement e.g. Div where content is loaded into
	 */
	initialize : function(windowElement,frameElement){
		var obj = this;
		this.mask = new Mask();
		this.frame = frameElement;
		this.initFrame();
		this.container = windowElement;
		this.container.pin();
		this.container.set('tween', {duration: 'short'});
		// this.title = this.container.getElement('#winTitle');
		this.closeLnk = this.container.getElement('#winClose');
		this.closeLnk.addEvent('click',function(){obj.close();});
		if(screen.height > 768){
			window.addEvent('scroll',function(e){
				obj.fixPosition();
			});
		}else{
			this.mask.addEvent('click',function(){
				new Fx.Scroll(window).toElement(obj.container);
			});
		}
		left = (screen.width - 564) / 2;
		this.container.setStyle('left',left);
	},
	
	/**
	 * Fixes lightbox to screen
	 */
	fixPosition : function(){
		this.container.setStyle('top',((this.getScrollOffset())+20)+'px');
	},
	
	/**
	 * Get scroll offset
	 */
	getScrollOffset : function(){
		var scroll = 0;
		if( typeof( window.pageYOffset ) == 'number' ) {
		    //Netscape compliant
			scroll = window.pageYOffset;
		  } else if( document.body && ( document.body.scrollLeft || document.body.scrollTop ) ) {
		    //DOM compliant
			 scroll = document.body.scrollTop;
		  } else if( document.documentElement && ( document.documentElement.scrollLeft || document.documentElement.scrollTop ) ) {
		    //IE6 standards compliant mode
			 scroll = document.documentElement.scrollTop;
		  }
		return scroll; // window.pageYOffset
	},
	
	/**
	 * Init the dynamic div which will act like an iframe
	 */
	initFrame : function(){
		var obj = this;
//		this.frame.addEvent('click:relay(a)',function(e){
//			e.stop();
//			obj.loadHref(this.get('href'));
//		});
		this.frame.addEvent('submit:relay(form)',function(e){
			var frm = this;
			if(!frm.get('target')){
				e.stop();
				var req = new Request.HTML({
					method: frm.get('method') || 'post',
					url: frm.get('action'), 
					data: frm
				});
				this.store('send', req);
				req.addEvent('onSuccess',function(resp){
					obj.loadResponse(resp);
				});
				req.send();
			}
		});
	},
	
	/**
	 * Load URL contents into lightbox view
	 * @param href string
	 */
	loadHref : function(href){
		if(!href) return;
		this.show();
		var obj = this;
		this.frame.empty();
		this.frame.addClass('loading');
		this.req = new Request.HTML({
			url : href,
			method : 'get',
			onSuccess : function(resp){
				obj.frame.removeClass('loading');
				obj.loadResponse(resp);
			},
			onFailure : function(resp){
				obj.frame.removeClass('loading');
				alert('Sorry this page is not available at this time, please try again later.');
				obj.close();
			}
		}).send();
	},
	
	/**
	 * Load JSON Response into lightbox
	 */
	loadResponse : function(resp){
		if(resp){
			this.frame.adopt('html',resp);
			var newLinks = this.frame.getElements('a');
			newLinks.each(function(link){
				attachLinkEvents(link);
			});
			var inputs = this.frame.getElements('input');
			if(inputs && inputs[0]){
				var firstInp = inputs[0].get('id');
				setTimeout('$("'+firstInp+'").focus()',500);
			}
		}
	},
	
	/**
	 * Show mask and window
	 */
	show : function(){
		this.mask.show();
		this.fixPosition();
		this.container.setStyle('display','block');
		this.container.set('opacity',0);
		this.container.fade('in');
	},
	
	/**
	 * Hide mask and window
	 */
	hide : function(){
		this.container.fade('out');
		this.mask.hide();
	},
	
	/**
	 * Close window+mask and reset contents
	 */
	close : function(){
		this.hide();
		var obj = this;
		this.container.retrieve('tween').chain(function(){
			obj.frame.empty();
		});
	}
});

/**
 * Forward lightbox
 * @param href
 */
function forwardLightbox(href){
	var lb = window.retrieve('lightbox');
	if(lb){
		lb.loadHref(href);
	}
}

/**
 * Used when you have to return form errors via iframe (e.g. ajax style file uploads)
 * @param errors
 */
function setFormErrorsInLightbox(errors){
	var lb = window.retrieve('lightbox');
	if(lb){
		for(var n=0;n<errors.length;n++){
			var el = $(errors[n]);
			if(el){
				el.addClass('lbError');
			}
		}
		alert("Please check the form for errors");
	}
}

/**
 * Take a link and attach standard events to it
 */
function attachLinkEvents(link){
	// Add Lightbox Open Events
	if(link.hasClass('lightbox')){
		link.addEvent('click',function(e){
			e.stop();
			var lBox = window.retrieve('lightbox');
			if(!lBox){
				lBox = new LightBox($('window'),$('ajaxFrame'));
				window.store('lightbox',lBox);
			}
			//var scrollOffset = window.pageYOffset;
			lBox.loadHref(this.get('href'));
		});
	}
	
	// Add Scroll To Anchor Events
	if((link.get('href')+'').contains('#') && !link.hasClass('dontScroll')){
		link.addEvent('click',function(e){
			var parts = (link.get('href')).split('#');
			var target = (parts[1]) ? parts[1] : null;
			var targetEl = null;
			if(target){
				e.stop();
				new Fx.Scroll(window).toElement($(target));
			}
		});
	}
	
	// Add Dynamic Loaders
	if(link.hasClass('loadDynamically') && link.get('rel')){
		var target = $(link.get('rel'));
		var loader = new DynamicLoader(target);
		link.addEvent('click',function(e){
			e.stop();
			var linkParent = link.getParent();
			// Portfolio specific shenanigans
			var portfolioTitle = $('portfolioSectionTitle');
			if(portfolioTitle){
				var parentUl = linkParent.getParent('ul');
				if(parentUl){
					parentUl.getChildren().removeClass('active');
					linkParent.addClass('active');
					$('loadMoreBtn').set('href',link.get('href')).set('title',link.get('text'));
				}
				portfolioTitle.set('text',(link.get('title') ? link.get('title') : link.get('text')));
			}
			loader.update(link.get('href'));
		});
	}
	
	// Add target="_blank" to external links
	if(link.get('rel') && (link.get('rel')+'').contains('external')){
		link.set('target','_blank');
	}
	
	// Add iphone preview windows
	if(link.hasClass('iphone')){
		link.addEvent('click',function(e){
			e.stop();
			var iphone = new IphoneBrowser(link.get('href'));
			iphone.container.setStyles({'left':(e.page.x-200)+'px','top':(e.page.y-300)+'px'});
		});
	}
}
