var nameSpace = {
	checkEmail: function(email){
		if(email.value !== '') {
			if((email.value.indexOf(".") === -1) || (email.value.indexOf("@") === -1)) {
				alert("Please enter a valid email address!");
				email.style.backgroundColor = "lightyellow";
				window.setTimeout(function(){
					email.focus();
					email.select();
				}, 0);
				return false;
			}
		}
	},
	createShim: function () {
		var body = document.getElementsByTagName('body')[0],
			shim = document.createElement('div'),
			winHeight = $( window ).height(),
			wrapHeight = $( '#wrapper' ).height();
			
		shim.id = 'shim';
		body.appendChild(shim);		
		$( shim ).css('height', ( wrapHeight > winHeight ? wrapHeight : winHeight ) );
	},
	removeShim: function () {
		$("#shim").remove();
	},
	contactFormResponse: function ( data ) {
		$("#contact_form").html( data );
		$(".close").closeElement( opts = { remove: true, elem: '#contact_form' } );
	},
	openClose: function ( el ) {
		if( $( el ).next().hasClass( "hidden" ) ) {
			$( el ).next().removeClass( "hidden" );
		} else {
			$( el ).next().addClass( "hidden" );
		}
	},
	replaceBackgroundImage: function ( el, image1, image2 ) { 
		var backgroundImage =  $( el ).css( 'backgroundImage' ); 
		if( backgroundImage.match(image1) ) { 
			backgroundImage = backgroundImage.replace(image1, image2);
			el.style.backgroundImage = backgroundImage;
		} else {
			backgroundImage = backgroundImage.replace(image2, image1);
			el.style.backgroundImage = backgroundImage;
		}
	},
	slide: function ( el, opts ) { 
		var opts = opts || {}, openElems, openElem, 
			$el = $( el ), image1, image2, toggle = false; 
		if( typeof opts.toggle === 'object' ) {
			toggle = true;
			image1 = opts.toggle.image1;
			image2 = opts.toggle.image2;
		}
		if( $el.next().hasClass( "hidden" ) ) {
			$el.next().slideDown();
			$el.next().removeClass( "hidden");
			if( opts.closeOthers ) {
				openElems = $el.parent().children( '.open' );
				$( openElems ).each( function() {
					$( this ).next().slideUp();
					$( this ).next().addClass( "hidden");
					$( this ).removeClass( "open" );
					if( toggle ) {
						nameSpace.replaceBackgroundImage( this, image1, image2 );
					}
				} );
				$el.addClass( 'open' );
			} 
			if( toggle ) { 
				nameSpace.replaceBackgroundImage( el, image1, image2 );
			}
		} else {
			$el.next().slideUp();
			$el.next().addClass( "hidden");
			if( $el.hasClass( "open" ) ) {
				$el.removeClass( "open" );
			}
			if( toggle ) {
				nameSpace.replaceBackgroundImage( el, image1, image2 );
			}
		}
	},
	showLoader: function ( element ) {
		var loader = document.createElement('img'),
			$loader = $( loader ),
			body = document.getElementsByTagName('body')[0];

		loader.src = "/images/site_images/ajax-loader.gif";
		loader.id = "loader";
		//body.appendChild( loader );
		element[0].appendChild( loader );
		//$( loader ).css('top', Math.ceil( ( $(window).scrollTop() + ( $( window ).height() - 19 ) / 2 ) ) );
		//$( loader ).css('left', ( $( element ).position().left + 500 +'px') );
		$loader.css('top', Math.ceil( ( $( element ).height() - 50 ) / 2 ) );
		$loader.css('left', ( $( element ).position().left + ( $( element ).width()  + 150 ) / 2 ) );
		$loader.css('margin', '0 auto');
		$loader.css('display', 'block');
		$loader.css('position', 'absolute');
	},
	hideLoader: function () {
		$("#loader").remove();
	},
	resizeImage: function ( image, container ) { 
		var $image = $( image ), $container = $( container );
		//container = element to size against eg. window, parent div, etc.
		if( $container === null || $container === undefined ) {
			$container = window;
		} 
		//if the image is wider or taller than the window or container
		if( $image.width() + 90 > $container.width() || $image.height() + 230 > $(window).height() ) { 
			if( $image.width() > $container.width() - 90 ) { 
				if( $container.width() - 90 > 300 ) {
					$image.css('width', $container.width() - 92 ); 
				} else {
					$image.css( 'width', 300 );
				}
				$image.css('height','auto');
			} 
			if( $image.height() + 230 > $(window).height() ) {
				if( $(window).height() - 230 > 300 ) {
					$image.css('height', $(window).height() - 230 );
				} else {
					$image.css( 'height', 300 );
				}
				$image.css('width','auto');
			} //if the image's css width & height is less than the image's width & height, and less than the window width & height
		} else if( ( $image.width() < $image[0].naturalWidth && $image.width() + 90 < $container.width() ) && ( $image.height() < $image[0].naturalHeight && $image.height() + 230 < $(window).height() ) ) {
			$image.css('height', $(window).height() - 230 );
			$image.css('width','auto');
		}  
		//set the width of the gallery to the width of the image
		$("#gallery").css('width', $image.width() );
	},
	positionElement: function ( element ) { 
		$(element).css('top', Math.ceil( ( $(window).scrollTop() + ( $(window).height() - $(element).outerHeight() ) / 2 ) ) + 'px' );
	},
	showGallery: function ( url ) { 
		var gallery = $( "#gallery_wrap" ),
			body = $( "body" ),
			img;
		   
		if( gallery[0] === undefined ) { 
			gallery = document.createElement('div');
			gallery.id = 'gallery_wrap';
			gallery.className = '';
			body[0].appendChild(gallery);   
		} 
		$( gallery ).css('visibility', 'hidden'); 
		nameSpace.showLoader( $("#shim") );
		$( gallery ).load( url, {}, function() { 
			$(".img_number").imgNumClickHandler(); 
			$(".arrow").imgNumClickHandler();           
			$( $("#main_image > img")[0] ).load( function() { 
				nameSpace.resizeImage( $("#main_image > img") );
				nameSpace.positionElement( gallery );
				$(".close").closeElement( opts = { remove: true, resize: true, elem: '#gallery' } );            
				$(window).resize( function() { 
					nameSpace.resizeImage( $("#main_image > img") );   
					nameSpace.positionElement( gallery );
				} );                
				nameSpace.hideLoader();
				$( gallery ).css('visibility', 'visible');
			} );
		} );     
	},
	showContactForm: function ( url ) {
		var contactForm = $( "#contact_form" );
			body = $( "body" );
		
		if( contactForm[0] === undefined ) { 
			contactForm = document.createElement('div');
			contactForm.id = 'contact_form';
			contactForm.className = '';
			body[0].appendChild(contactForm);
		} else {
			contactForm.removeClass("hidden");
		}
		$( contactForm ).load( url, {}, function() { 
			$(".close").closeElement( opts = { remove: true, elem: '#contact_form' } );
			$( "#contact_form > form" ).contactFormSubmit();
		} );
	},
	storage: {
		isSupported: function () {
			try {
				return ('localStorage' in window && window['localStorage'] !== null);
			} catch (e) {
				return false;
			}
		},
		get: function ( key ) {
			return localStorage.getItem(key);
		},
		store: function () {
			try {
				localStorage.setItem(key, value);
				//or localStorage[key] = value; //like associative arrays
			} catch (e) {
				alert(e.Description);
				return -1;
			}
		},
		remove: function () {
			return localStorage.removeItem(key);
		},
		clear: function() {
			return localStorage.clear();
		}
	}
};

$.fn.extend( {
	closeElement: function ( opts ) { 
		var element = $( opts.elem );
		
		if( element ) { 
			this.bind( "click", function(e) { 
				if( opts.remove === true ) {
					$( element ).remove();
				} else { 
					element.addClass("hidden");
				}   
				if( opts.resize === true ) {
					$(window).unbind("resize");
				}              
				nameSpace.removeShim();
				e.preventDefault();
			} );
		}
	},
	viewWorkClickHandler: function () {
		this.bind( "click", function(e) {
			e.preventDefault();
			nameSpace.createShim();
			nameSpace.showGallery( this.href );
		} );
	},
	emailClickHandler: function () {
		this.bind( "click", function(e) {
			nameSpace.showContactForm( '/home/contact_ajax_form' );
			nameSpace.createShim();
			e.preventDefault();
		} );
	},
	imgNumClickHandler: function () { 
		var gallery = $("#gallery");
		
		if( gallery[0] !== undefined ) {
			this.bind( "click", function(e) { 
				//added for IE
				$("#gallery").css('visibility', 'hidden');
				nameSpace.showGallery( this.href );
				e.preventDefault();
			} );
		}
	},
	contactFormSubmit: function () {
		this.bind("submit", function(e) {      
			$.ajaxSetup ({
				cache: false
			} );
			e.preventDefault();
			$.post( "send_contact", $("#contact_form > form").serialize(), function( data, textStatus ) { nameSpace.contactFormResponse( data ); }, "html" );        
		} );
	},
	moreClickHandler: function () { 
		this.bind("click", function(e) { 
			nameSpace.slide( $(this).parent() );
			if( $( this ).html() === 'More...' ) {
				$( this ).html( 'Less...' );
			} else {
				$( this ).html( 'More...' );
			}
			e.preventDefault();
		} );
	},
	navClickHandler: function() {
		this.bind("click", function(e) {
			e.preventDefault();
			$(this).siblings('ul.sub_nav').slideToggle();
		} );
	},
	loadImage: function ( opts ) { 
		var gallery = this,
			ns = nameSpace,
			$img = $( "img", this ),
			$main = $( "#main" ),
			$mainCont = $( "#main_content" ),
			$newImage, opts = opts || {},
			mainHeight, storage = ns.storage.isSupported(),
			resize = ( opts.resize != undefined ? opts.resize : true ),
			showLoader = ( opts.showLoader != undefined ? opts.showLoader : true );
		
		function positionGallery () { 
			$( "p", gallery ).css( 'width', $newImage.width() ); 
			$( gallery ).css( 'margin-left', ( $( "#main_content" ).width() - $( gallery ).width() ) /2 );
			$( ".arrow", gallery ).css( 'height', $newImage.css('height') );
			$( "a span", gallery ).css( 'margin-top', $newImage.height()/2 - 24 );
		}
	
		if( gallery.length !== 0 ) {
			$(window).unbind("resize");
			$( "#main_image, .main_image" ).css( 'visibility', 'visible' );
			$newImage = $img.clone();
			if( resize ) {
				$main.css('height', 'auto' );
			}
			$( gallery ).hide();
			if( showLoader ) {
				ns.showLoader( $main );
			}
			$img.before( $newImage );
			$img.remove();
			$newImage.load( function() {
				if( showLoader ) {
					ns.hideLoader();
				}
				
				$main.css('height', 'auto');
				$( gallery ).fadeIn( 'slow' );
				if( resize ) {
					ns.resizeImage( $newImage, $mainCont );
					$main.css('height', $newImage.height() + 50 );
					positionGallery();
					$(window).resize( function() { 
						ns.resizeImage( $newImage, $mainCont );  
						$main.css('height', $newImage.height() + 50 );
						positionGallery();
					} );
				}
			} );
		}
	},
	toggleClickHandler: function ( opts ) {
		this.bind( "click", function(e) { 
			nameSpace.slide( this, opts ); 
		} );
	},
	showDescription: function () {
		var $cat_description = $('#category_description');
		if( !$cat_description.hasClass('hidden') ) {
			$cat_description.remove().appendTo('body');
			$cat_description.css('left', ( $(window).width() / 2 ) - ( $(this).width() / 2 ) );
			nameSpace.createShim();
		}
	}
} );

$(document).ready( function() {
	var $main_image = $( '#main_image' ),
		$_main_image = $('.main_image'),
		$cat_description = $('#category_description');
	$("#email").emailClickHandler();
	$("#view_work").viewWorkClickHandler();
	$("#main_nav a.more").navClickHandler();
	if( $main_image.length ) {
		$main_image.loadImage();
	}
	if( $_main_image.length ) {
		$_main_image.each( function() { $( this ).loadImage( { "resize": false, "showLoader": false } ); } );
	}
	$(".toggle").toggleClickHandler( { "closeOthers": true, "toggle": { "image1": "sm_open", "image2": "sm_close" } } );
	$('#email_address').live('blur', function(){
		nameSpace.checkEmail(this);
	});
	if( $cat_description.length ) {
		$cat_description.showDescription();
		$(".close").closeElement( opts = { elem: $cat_description } );
	}
	$('#shim').live('click', function() {
		$(this).remove();
		$('.close').click();
	});
} );

