// Need to include jquery before calling this script
var API = {

	divToUpdate: 'content_container',
	divToCenter: '',
	afterRender: '',
	bodyOverlayImg: '',
	width: 0,
	height: 0,
	afterFormRender: '',
	customLinkFire: '',
	customFormSubmit: '',
	customSubmit: false,
	isHidden: true,
	centerVertically: true,
	redirectOnHashChange: true,
	validation: new Array(),
	currentUrl: '',

	init: function(){
		this.ajax.adult = this;
		this.originalDivToUpdate = this.divToUpdate;
		this.originalCenterVertically = this.centerVertically;
	},

	getDivToCenter: function() {
		if(this.divToCenter	&& this.divToCenter!='') {
			return this.divToCenter;
		} else {
			return this.divToUpdate;
		}
	},

	showBodyOverlay: function() {
		if($('#body_overlay').is(':hidden')) {
			$('#body_overlay').removeClass('hidden');
		}
		else if(this.isHidden && this.bodyOverlayImg && this.bodyOverlayImg!='') {
			inserttext = '<div id="body_overlay" style="width:100%;height:100%;position:absolute;left:0;top:0;background:url('+this.bodyOverlayImg+') repeat;">&nbsp;</div>';
			$(inserttext).prependTo('body');
		}
	},

	hideBodyOverlay: function() {
		if(this.bodyOverlayImg && this.bodyOverlayImg!='') {
			$('#body_overlay').addClass('hidden');
		}
	},

	setViewVars: function(data, view_vars) {
		for (var key in view_vars) {
			data = data.replace('{' + key +'}', view_vars[key]);
		}

		return data;
	},

	view: function(name, view_vars){
		updateBox = this.updateBox;
		adult = this;

		// Shouldn't call view if link is javascript:void(0) for example
		if(name.match('javascript')) {
			return false;
		}

		// Don't change url for error modals and javascript links
		if(!name.match('error') && !name.match('javascript')) {
			this.currentUrl = name;
		}

		// If hash is blank then no ajax request is needed
		if(name == '') return false;

		// All is good at this point, process the request
		$.get(name, function(data) {
			if(adult.isHidden) {
				adult.showBodyOverlay();
			}

			// Set view vars if they exist
			if(view_vars) {
				data = adult.setViewVars(data, view_vars);
			}

			$('#'+adult.divToUpdate).html(data);
			try{
				if($('#'+adult.getDivToCenter()).attr('class').match('centered')) {
					adult.center();
				}
			}catch(err) {
				// alert('error')
			};
			if(adult.isHidden)
			{
				adult.show();
			}
			adult.ajax.init();
			this.centerVertically = this.originalCenterVertically;
		});
	},

	centerWidth: function()
	{
		if(this.width) {
			screenWidth = this.width;
		} else {
			screenWidth = getSize('width');
		}
		divelement = $("#"+this.getDivToCenter());
		divwidth = divelement.width();
		leftvalue = ((screenWidth/2 - ( divwidth / 2 )) + 'px');
		divelement.css('left', leftvalue );
	},

	centerHeight: function()
	{
		if(this.height) {
			screenHeight = this.height;
		} else {
			screenHeight = getSize('height');
		}
		divelement = $("#"+this.getDivToCenter());
		divheight = divelement.height();
		topvalue = (screenHeight/2 - ( divheight / 2 ));

		if(topvalue < 0) {
			topvalue = 20;
		}

		topvalue += 'px';
		divelement.css('top', topvalue );
	},

	center: function()
	{
		this.centerWidth();
		if(this.centerVertically) {
			this.centerHeight();
		} else {
			this.centerVertically = this.originalCenterVertically;
		}
	},

	show: function()
	{
		if(this.isHidden)
		{
			this.isHidden = false;
			//$("#"+this.divToUpdate).fadeIn('slow', function() {
			// Animation complete
			//	$("#"+this.divToUpdate).removeClass('hidden');
			//});
			$("#"+this.divToUpdate).removeClass('hidden');
		}
	},

	hide: function(){
		if(!this.isHidden)
		{
			this.isHidden = true;
			$("#"+this.divToUpdate).addClass('hidden');
			this.hideBodyOverlay();
			this.setHash('');
		}
	},

	getRelativeUrl: function(input_url, debug) {
		linkto = input_url.replace(document.location.protocol+'//', '');
		linkto = linkto.replace( document.location.host + '/', '');
		// Remove starting forward slash
		if(linkto.substr(0,1) == '/') {
			linkto = linkto.substr(1, linkto.length - 1);
		}
		return linkto;
	},

	getHash: function(input_url) {
		return input_url;
	},

	setHash: function(name) {
		document.location.hash = name;
	},

	ajax: {
		init: function(){
			this.links();
			this.forms();
		},

		links: function(){
			overlaylinks = $('div#'+API.divToUpdate+' a');
			for(i=0; i<overlaylinks.length; i++)
			{
				isTargetBlank = $(overlaylinks[i]).attr('target') && $(overlaylinks[i]).attr('target') == '_blank';
				if ($(overlaylinks[i]).attr('href')) {
					isHrefEmpty = API.getRelativeUrl($(overlaylinks[i]).attr('href')) == '#';
					var lastChar = $(overlaylinks[i]).attr('href').charAt($(overlaylinks[i]).attr('href').length - 1);
					if (lastChar == '#')	isHrefEmpty = true;
				}
				if(!$(overlaylinks[i]).attr('noajax') && !isTargetBlank && !isHrefEmpty) {
					$(overlaylinks[i]).click(function(){
						linkto = API.getRelativeUrl(this.href, true);
						hashlink = API.getHash(linkto);
						if(API.originalDivToUpdate == API.divToUpdate && !hashlink.match('javascript')) {
							API.redirectOnHashChange = true;
							API.setHash(hashlink);
						} else {
							API.view(linkto);
						}
						return false;
					});
				}
			}
		},

		post: function(url, data){
			adult = this.adult;
			adult.redirectOnHashChange = false;
			linkto = adult.getRelativeUrl(url);
			hashlink = adult.getHash(linkto);
			$.ajax({
				type: 'POST',
				url: url,
				data: data,
				success: function(output) {
					$('#'+adult.divToUpdate).html(output);
					if(adult.isHidden)
					{
						//adult.show();
					}
					API.ajax.init();
					//adult.redirectOnHashChange = true;
				},
				complete: function(xhr) {
					adult.redirectOnHashChange = false;
					linkto = adult.getRelativeUrl(xhr.getResponseHeader('URL'));
					hashlink = adult.getHash(linkto);
					if(adult.currentUrl != hashlink) {
						adult.setHash(hashlink);
					}
				}
			});

		},

		get: function(url, data){
			if(url.match(/\?/g))
			{
				url = url + '&' + data;
			}
			else
			{
				url = url + '?' + data;
			}

			this.adult.view(url);
		},

		linkClick: function() {

		},

		formSubmit: function(obj) {
			if($(obj).attr('target')) {
				return $(obj).submit();
			}
			data = $(obj).serialize();

			if(obj.method && obj.method.toLowerCase()=='post')
			{
				this.post(obj.action, data);
			}else{
				this.get(obj.action, data);
			}
			return false;
		},

		forms: function(){
			ajax = this;
			overlaylinks = $('div#'+API.divToUpdate+' form');
			for(i=0; i<overlaylinks.length; i++)
			{
				if(API.customSubmit == false) {
					$(overlaylinks[i]).submit(function(){
						if(API.customFormSubmit && API.customFormSubmit != '') {
							API.obj = this;
							eval(API.customFormSubmit);
						} else {
							ajax.formSubmit(this);
						}

						return false;
					});
				}

				if(API.afterFormRender && API.afterFormRender != '') {
					API.obj = $(overlaylinks[i]);
					eval(API.afterFormRender);
				}
			}
		}
	},

	showCheckout: function(){
		this.view('views/checkout.html');
	}


};

$(document).ready(function(){
	API.init();
	API.divToUpdate = 'main_container';
	API.ajax.init();
	API.divToUpdate = 'content_container';
});