var LightboxHolder = {	
	DestroyCreate:function( id , cClass ) {
		if( typeof( cClass ) == "undefined" ) {
			cClass="";
		}
		if( $('boxContents') ) {
			$('boxContents').update("&nbsp;")
		}
		
		if( $( id ) ) {
			$( id ).remove();			
		}
		if( !$( id ) ) {
			Element.extend( document.getElementsByTagName("body")[0] ).insert("<div class='" + cClass + "' id='" + id + "' style='display:none'></div>");
		}
	},
	Close:function( doConfirm ) {
		if( typeof( doConfirm ) == "undefined" ) {
			doConfirm = false;
		}
		if( doConfirm ) {
			var confirmation = confirm("Are you sure you want to cancel?");
			if( confirmation ) {
				Element.hide('box');
				Element.hide('dcoverlay');
			}
		} else {
			Element.hide('box');
			Element.hide('dcoverlay');
		}
	}
}

var Protofade = Class.create({

	initialize: function(element, options) {		
		this.options = {
      		Duration: 1,
			Delay: 4.0,
			Random: false,
			Slideshow:true,
			Controls:false
    	}
		Object.extend(this.options, options || {});

    	this.element        = $(element);
		this.slides			= this.element.childElements();
		this.num_slides		= this.slides.length;		
		this.current_slide 	= (this.options.Random) ? (Math.floor(Math.random()*this.num_slides)) : 0;
		this.end_slide		= this.num_slides - 1;
		
		this.slides.invoke('hide');
		this.slides[this.current_slide].show();
				
		if (this.options.Slideshow) { 
			this.startSlideshow();
		}				
		if (this.options.Controls) {
			this.addControls();
		}		
	},
	
	addControls: function() {
		this.wrapper 		= this.element.up();
		this.controls		= new Element('div', { 'class': 'controls' });
		this.wrapper.insert(this.controls);
		
		this.btn_next 		= new Element('a', { 'class': 'next', 'title': 'Next', href: '#' }).update('Next');
		this.btn_previous	= new Element('a', { 'class': 'previous', 'title': 'Previous', href: '#' }).update('Previous');
		this.btn_start		= new Element('a', { 'class': 'start', 'title': 'Start', href: '#' }).update('Start');
		this.btn_stop		= new Element('a', { 'class': 'stop', 'title': 'Stop', href: '#' }).update('Stop');
		
		this.btns = [this.btn_next, this.btn_previous, this.btn_start, this.btn_stop];
		this.btns.each(function(el){
			this.controls.insert(el);
		}.bind(this));
		
		this.btn_previous.observe('click', this.moveToPrevious.bindAsEventListener(this));
		this.btn_next.observe('click', this.moveToNext.bindAsEventListener(this));
		this.btn_start.observe('click', this.startSlideshow.bindAsEventListener(this));
		this.btn_stop.observe('click', this.stopSlideshow.bindAsEventListener(this));
	},

	startSlideshow: function(event) {
		if (event) { Event.stop(event); }
		if (!this.running)	{
			this.executer = new PeriodicalExecuter(function(){
	  			this.updateSlide(this.current_slide+1);
	 		}.bind(this),this.options.Delay);
			this.running=true;
		}
	},
	
	stopSlideshow: function(event) {	
		if (event) { Event.stop(event); } 
		if (this.executer) { 
			this.executer.stop();
			this.running=false;
		}	 
	},

	moveToPrevious: function (event) {
		if (event) { Event.stop(event); }
		this.stopSlideshow();
  		this.updateSlide(this.current_slide-1);
	},

	moveToNext: function (event) {
		if (event) { Event.stop(event); }
		this.stopSlideshow();
  		this.updateSlide(this.current_slide+1);
	},
	
	updateSlide: function(next_slide) {
		
		if (next_slide > this.end_slide) { 
				next_slide = 0; 
		} 
		else if ( next_slide == -1 ) {
				next_slide = this.end_slide;
		}
		
		this.fadeInOut(next_slide, this.current_slide);		
	},

 	fadeInOut: function (next, current) {		
		this.slides[current].setStyle({"zIndex":1});
		this.slides[next].setStyle({"zIndex":15});
		new Effect.Parallel([
			new Effect.Fade(this.slides[current], { sync: true }),
			new Effect.Appear(this.slides[next], { sync: true }) 
  		], { duration: this.options.Duration });
		
		this.current_slide = next;		
	}

});

var pf = null;
var GOS = {
	Lightbox : {
		ShowImage:function(imageId) {
			var url = "index.cfm?action=Carousel_ShowImage&id=" + imageId;
			new Ajax.Request( url, {asynchronous:true, onSuccess:GOS.Lightbox.ShowImage_onSuccess, onFailure:errFunc});
		},
		ShowImage_onSuccess:function(t) {
			z = parseJSON( t.responseText );
			LightboxHolder.DestroyCreate("LightboxHolder","plain");		
			$("LightboxHolder").update( z.imageHTML );
			DCLightbox.showBoxByID( "LightboxHolder", 650, 550, false );
		}
	},
	Homepage : {
		Carousel : {
			Start:function() {
				var c = new UI.Carousel("horizontal_carousel");
			}
		}
	},
	HomePageWidget : {		
		Start:function( argSlideSpeed ) {
			pf = new Protofade("headerPhoto" , {Duration:argSlideSpeed});
		}
	},
	HAL:function(id) {
		new Effect.Highlight( $(id) );
		$(id).focus();
	},
	Contact : {
		Validate:function() {
			if( $("contactName").value.blank() ) {
				GOS.HAL("contactName");
				return false;
			}
			if( $("contactEmail").value.blank() ) {
				GOS.HAL("contactEmail");
				return false;
			}
			if( $("contactPhone").value.blank() ) {
				GOS.HAL("contactPhone");
				return false;
			}
			if( $("contactEnquiry").value.blank() ) {
				GOS.HAL("contactEnquiry");
				return false;
			}
			return true;
		}
	},
	MyAccount : {
		Query : {
			Validate:function() {
				if( $("designQuery").value.blank() ) {
					GOS.HAL("designQuery");
					return false;
				}
				return true;
			}
		},
		PreOrder : {
			Validate:function() {
				if( $("enquiryMessage").value.blank() ) {
					GOS.HAL("enquiryMessage");
					return false;
				}
				return true;
			}
		},
		Amnesia : {
			Validate:function() {
				if( $("emailaddress").value.blank() ) {
					GOS.HAL("emailaddress");
					return false;
				}
				return true;
			}
		},
		MyDetails : {
			Countries : {
				onChange:function() {					
					if( $("countryId") ) {						
						if( $("countryId").value == 1 ) {							
							if( $("countyHolder") ) {
								$("countyHolder").show();
							}
						} else {
							$("countyHolder").hide();
						}
					}
				}
			},
			Validate:function() {
				if( $("firstname").value.blank() ) {
					GOS.HAL("firstname");
					return false;
				}
				if( $("lastname").value.blank() ) {
					GOS.HAL("lastname");
					return false;
				}
				if( $("address").value.blank() ) {
					GOS.HAL("address");
					return false;
				}
				if( $("emailAddress").value.blank() ) {
					GOS.HAL("emailAddress");
					return false;
				}
				if( $("password").value.blank() ) {
					GOS.HAL("password");
					return false;
				}
				if( $("password2").value.blank() ) {
					GOS.HAL("password2");
					return false;
				}
				if( $("password").value!=$("password2").value ) {
					alert("Your password and the confirmation password are not the same");
					return false;
				}
				return true;
			}
		},
		Login : {
			Validate:function() {
				if( $("emailaddress").value.blank() ) {
					GOS.HAL("emailaddress");
					return false;
				}
				if( $("password").value.blank() ) {
					GOS.HAL("password");
					return false;
				}
				return true;
			}
		}
	},
	SpaceMaker : {
		Account : {
			Validate:function() {
				if( $("firstname").value.blank() ) {
					GOS.HAL("firstname");
					return false;
				}
				if( $("lastname").value.blank() ) {
					GOS.HAL("lastname");
					return false;
				}
				if( $("emailAddress").value.blank() || $("emailAddress").value.indexOf("@") == -1 ||  $("emailAddress").value.indexOf(".") == -1 ) {
					GOS.HAL("emailAddress");
					return false;
				}
				$("btnSubmit").disabled = true;
				new Ajax.Request('index.cfm', {asynchronous:true, onSuccess:GOS.SpaceMaker.Account.Validate_onSuccess, onFailure:errFunc, parameters:Form.serialize( $( "myAccountRegisterForm" ) )});
				return false;
			},
			Validate_onSuccess:function(t) {
				z = parseJSON( t.responseText );
				if( z.message ) {
					alert( z.message );
					$("btnSubmit").disabled = false;
				} else {
					$("LightboxHolder").update( z.designToolHTML );
				}
			}
		},
		Launch:function(argId,argUID) {
			if(	typeof( argId ) == "undefined" ) {
				argId = 0;
			}
			if(	typeof( argUID ) == "undefined" ) {
				argUID = 0;
			}
			if( pf ) {
				pf.stopSlideshow();
			}
			var url = "index.cfm?action=SpaceMaker_Launch&spaceMakerDesignId=" + argId + "&userId=" + argUID;
			new Ajax.Request( url, {asynchronous:true, onSuccess:GOS.SpaceMaker.Launch_onSuccess, onFailure:errFunc});
		},
		LaunchType:function(argId) {
			if(	typeof( argId ) == "undefined" ) {
				argId = 0;
			}
			if( pf ) {
				pf.stopSlideshow();
			}
			var url = "index.cfm?action=SpaceMaker_LaunchType&typeId=" + argId;
			new Ajax.Request( url, {asynchronous:true, onSuccess:GOS.SpaceMaker.Launch_onSuccess, onFailure:errFunc});
		},
		Launch_onSuccess:function(t) {
			z = parseJSON( t.responseText );
			LightboxHolder.DestroyCreate("LightboxHolder");		
			$("LightboxHolder").update( z.designToolHTML );
			DCLightbox.showBoxByID( "LightboxHolder", 1000, 650, false );
		},
		Close:function(bMsg) {
			if( typeof(bMsg)=="undefined" ) {
				bMsg = true;
			}
			if( bMsg ) {
				var confirmation = confirm("You are about to leave SpaceMaker.\n\n\Any unsaved changes will be lost.");
			} else {
				var confirmation = true;
			}
			if( confirmation ) {
				LightboxHolder.Close();
			}
			if( pf ) {
				pf.startSlideshow();
			}
		}
	}
}

String.prototype.isEmail = function () { 
	var rx = new RegExp("\\w+([-+.\’]\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*"); 
	var matches = rx.exec(this); 
	return (matches != null && this == matches[0]); 
}

function isNumeric(x) { 
	var y=parseInt(x); 
	if (isNaN(y)) {
	   return false; 
	} else {
		return true;
	}
} 

function LoadingAjax(txt) {
	if(typeof(txt)=="undefined") {
		txt = "Loading...";
	}
	return "<div class='ajaxMsg' id='widgetAjaxMsg'> "+txt+"</div>";
}

function parseJSON( json ){
	var o = eval('(' + json + ')');
	if( o.redirectURL )
	{
		document.location = o.redirectURL;
		return;
	}
	if( $("message") != null ) new Element.remove( "message" );
	if( o.errMsg )
	{
		if( o.errMsgTitle == null ) o.errMsgTitle = "Error";
		if( o.errMsgTimer == null ) o.errMsgTimer = 5000;
		tw.ShowMessage( o.errMsgTitle, o.errMsg, "error", o.errMsgTimer, o.errMsgPosition );
		return o;
	}
	if( o.msgTitle || o.msg )
	{
		if( o.msgTimer == null ) o.msgTimer = 5000;
		tw.ShowMessage( o.msgTitle, o.msg, o.msgClass, o.msgTimer, o.msgPosition );
	}
	return o;
}

var errFunc = function(t) {
	var win = window.open("", "win", "width=1024,height=700,resizable=yes,scrollbars=yes,status=no"); // a window object
	win.document.open("text/html", "replace");
	win.document.write( "<html><body style='margin:0'><div style='border-bottom:1px solid #222;background:#666;padding:10px;'><h1 style='color:#FFF;margin:0;padding:0;'>Digital Crew Ajax Error</h1></div><div style='padding:10px;'>"+t.responseText.replace(/^\s+|\s+$/, '') + "</div></body></html>" );
	win.document.close();
	win.focus();
}