/*
 * Libraries and third-party scripts/plugins goes here
 * For example: jQuery, sIFR, Lightbox
 */

// .......
 
/*
 * Scripts
 *
 */
var Engine = {
	// external links
	externalLinks : function(){
		$('a[@rel*=external]').attr('target','_blank');
	},
	// mails
	secureMails : function(){
		$('a[@href^=mailto:]').each(function(){
			var mail = $(this).attr('href').replace('mailto:','');
			var replaced = mail.replace('/at/','@');
			$(this).attr('href','mailto:'+replaced);
			if($(this).text() == mail) $(this).text(replaced);
		});
	},
	// headers
	replaceHeaders : function(){
		if(typeof sIFR == "function"){
			sIFR.replaceElement("#content h1.a", named({sFlashSrc: "/fonts/claderon.swf", sColor: "#ffffff", sLinkColor: "#ffffff", sHoverColor: "#ffffff", sWmode: "transparent"}));
			sIFR.replaceElement("#content h2.a", named({sFlashSrc: "/fonts/claderon.swf", sColor: "#ffffff", sLinkColor: "#ffffff", sHoverColor: "#ffffff", sWmode: "transparent"}));
			sIFR.replaceElement("#content h3.a", named({sFlashSrc: "/fonts/claderon.swf", sColor: "#ffffff", sLinkColor: "#ffffff", sHoverColor: "#ffffff", sWmode: "transparent"}));
		};
	},
	// shadow
	headerShadow : function(){
		var el = $('#header h2');
		el.after('<p class="shadow">'+ el.text() +'</p>');
	},
	// calculator
	calculator : {
		init : function(){
			this.pages 		= 1;
			this.done		= false;
			
			this.base = [];
			this.subs = [];

			this.prices();
			this.create();
			this.shortcuts();
			this.triggers();
			
			this.containerCurrency.eq(0).trigger('click');
		},
		// trigger the calculations and populate fields
		evaluate : function(){
			this.calculate();
			
			this.containerPages.text(this.pages);
			this.containerTotal.html(this.totalHTML);
			this.containerOrder.attr('href',this.containerCheckout + '/' + this.pages + '/' + this.abbr);
			
			if(this.done){
				this.containerFormPrice.html(this.totalHTML);
				this.containerFormPages.val(this.pages);
				this.containerFormCurrency.val(this.abbr);
			}
			this.done = true;
		},
		// grabs the prices from html
		prices : function(){
			$('#calculator div.data ul li span.additional').each(function(i){
				Engine.calculator.subs[i] = parseInt($(this).html());			
			});
			$('#calculator div.data ul li span.first').each(function(i){
				Engine.calculator.base[i] = parseInt($(this).html()) - Engine.calculator.subs[i];
			});
		},
		// replaces prices with slider
		create : function(){
			var code = '';
			
			code += '<p class="pages">How many pages? <span>1</span></p>' + "\n";
			code += '<ul class="slider"><li class="less"><a href="#less">-</a></li><li class="drag" id="slider"><span class="holder" id="knob">•</span></li><li class="more"><a href="#more">+</a></li></ul>' + "\n";
			code += '<div class="wrapper">';
			code += '<p class="total">Total: <span>0</span></p>';
			code += '<p class="currency">Change currency: <a href="#EUR" class="euro" title="EUR">&#8364;</a> &middot; <a href="#USD" class="dolar" title="USD">$</a> &middot; <a href="#GBP" class="pound" title="GBP">&#163;</a>';
			code += '</div>' + "\n";

			$('#calculator div.data').after(code).remove();
		},
		// sets shortcuts
		shortcuts : function(){
			// shortcuts
			this.containerPages 	= $('#calculator p.pages span');
			this.containerLess 		= $('#calculator ul.slider li.less a');
			this.containerMore		= $('#calculator ul.slider li.more a');
			this.containerCurrency	= $('#calculator p.currency a');
			this.containerTotal		= $('#calculator p.total span');
			this.containerOrder		= $('#calculator p.checkout a');
			this.containerCheckout	= this.containerOrder.attr('href');
			
			this.containerFormPrice		= $('#order strong.price');
			this.containerFormPages		= $('#f-pages');
			this.containerFormCurrency	= $('#f-currency');
		},
		// calculate the price
		calculate : function(){
			var base 		= this.base[this.currency];
			var page		= this.subs[this.currency];	
			this.total 		= this.pages * page + base;
			this.totalHTML 	= this.sign + '' + '' + this.total;
		},
		// add events
		triggers : function(){
			
			var parent = this;
		
			// currency change
			this.containerCurrency.click(function(e){
				 parent.currency = $(this).parent().find('a').index(this);
				 parent.sign = $(this).html();
				 parent.abbr = $(this).attr('href').replace('#','');
				 
				 $(this)
					.addClass('active')//.blur()
					.parent().find('a').not(this).removeClass('active');
					
					
				parent.evaluate();
				return false;
			});
			
			// less/more
			this.containerLess.click(function(){
				if(parent.pages <= 20){
					$('#slider').slider("moveTo","-=1");
				} else {
					parent.pages-= 1;
					parent.evaluate();
				}
				return false;
			});
			this.containerMore.click(function(){
				if(parent.pages < 20){
					$('#slider').slider("moveTo","+=1");
				} else {
					parent.pages+= 1;
					parent.evaluate();
				}
				return false;
			});
			
			// drag
			$('#slider').slider({
				handle : $('#knob'),
				minValue: 1, 
				maxValue: 20, 
				min: 1, 
				max: 20,
				stepping: 1,
				current: 1,
				slide: function(e, ui) { 
					parent.pages = ui.value;
					parent.evaluate();
				}
			});
			
		}
	},
	// faqs
	answersToggle : function(){
		$('dl.faq-a')
			.find('dd').hide().end()
			.find('dt').append('<span class="expand">expand</span>')
			.toggle(function(){
				$(this)
					.find('span').attr('class','collapse').html('collapse').end()
					.next('dd').fadeIn();
			},function(){
				$(this)
					.find('span').attr('class','expand').html('expand').end()
					.next('dd').fadeOut();
			});
	},
	// delicious link
	deliciousAdd : function(){
		$('#bookmarks li.delicious a').click(function(){
			window.open('http://del.icio.us/post?v=4&amp;noui&amp;jump=close&amp;url='+encodeURIComponent(location.href)+'&amp;title='+encodeURIComponent(document.title), 'delicious','toolbar=no,width=700,height=400'); 
			return false;
		});
	},
	// order form
	order : {
		init : function(){
			this.datepicker();
			this.change();
			this.templates();
			this.validate();
		},
		datepicker : function(){
			$('#f-deadline')
				.focus(function(){$(this).val('');})
				.datepicker({minDate: 3, showOn: "both", dateFormat: "dd/mm/yy", showAnim: "fadeIn", speed: "fast", buttonImage: "/images/icon-calendar-a.gif", buttonImageOnly: true});
		},
		change : function(){
			$('#f-pages')
				.after('<strong class="price"></strong>')
				.keyup(function(){
					var num = parseInt($(this).val());
					if(num > 0){
						if(num < 20) {
							$('#slider').slider("moveTo",num);
						} else {
							$('#slider').slider("moveTo",num);
							Engine.calculator.pages = num;
							Engine.calculator.evaluate();
						}
					} else {
						$(this).val(Engine.calculator.pages);
					}
				});
			$('#f-currency').change(function(){
				var current = $(this).get(0).selectedIndex;
				Engine.calculator.containerCurrency.eq(current).trigger('click');
			}).keyup(function(){
				var current = $(this).get(0).selectedIndex;
				Engine.calculator.containerCurrency.eq(current).trigger('click');
			});
			
			var currency = 0;
			if ($('#f-currency').get(0)) currency = $('#f-currency').get(0).selectedIndex || 0;
			var pages = parseInt($('#f-pages').val()) || 1;
			
			Engine.calculator.containerFormPrice = $('#order strong.price');
			
			$('#slider').slider("moveTo",pages);
			if(pages > 20){
				Engine.calculator.pages = pages;
				Engine.calculator.evaluate();
			}
			Engine.calculator.containerCurrency.eq(currency).trigger('click');
			
		},
		templates : function(){
			templates = 1;
			var cont = $('#f-template').parent();
			cont.append(' <img src="/images/icon-addfield.gif" width="16" height="16" alt="Add Field" title="Add Field" />')
			cont.find('img').click(function(){
				var parent = $(this).parent('p');
				if(parent.is(':animated')) return false;
				parent.clone().insertAfter(parent).hide().fadeIn('slow')
					.find('label').attr('for','template-'+templates).parent()
					.find('input').attr('id','template-'+templates).val('').parent()
					.find('img').remove();
				templates++;
				$(this).appendTo(parent.next('p'));
			});
		},
		validate : function(){
			Engine.errors = 0;
			$('#order').submit(function(){
				Engine.validation.clear($('#order'));
				Engine.validation.check($('#f-name'),Engine.validation.required,'Please enter your name');
				Engine.validation.check($('#f-email'),Engine.validation.email,'Please enter proper email address');
				Engine.validation.check($('#f-project'),Engine.validation.required,'Please enter project name');
				Engine.validation.check($('#f-pages'),Engine.validation.required,'Please enter pages count');
				Engine.validation.check($('#f-notes'),Engine.validation.required,'Please enter project notes');
				if(Engine.errors !== 0) return false;
				$(this).find('button').attr('disabled','disabled').blur().animate({ opacity: 0.4 }, 500);
			});
		},
		printout : function(){
			$('#ordered p.print span').wrapInner('<a href="#print"></a>').find('a').click(function(){
				window.print();
				return false;
			});
		},
		upload : function(){
		
			$('#upload-form').submit(function(){
				$(this).find('p.submit button')
					.attr('disabled','disabled')
					.animate({opacity: 0.4},500)
					.blur()
					.parent().after('<p class="wait">Uploading files... please wait</p>').parent().find('p.wait').fadeIn('slow');
				$('#template').attr('disabled','disabled');
			}).find('p.submit')
				.before('<h3 class="a">Upload Queue</h3><ul class="queue"><li class="empty">No files in queue yet</li></ul>')
				.find('span').html('Upload Files').end()
				.parent().find('h2.a').html('Insert your files');

			$('#template').change(function(){
				var path = $(this).val();
				var file = path.split('\\');
				file = file[file.length-1];
				
				var count = $('input.offset[type=file]').size()+1;
				
				$(this).clone().addClass('offset').attr('id','template-'+count).insertAfter($('input[type=file]:last'));
				$(this).val('');
				
				if(count <= 1){
					$(this).parent().parent().find('ul.queue li.empty').remove();
				}
				$(this).parent().parent().find('ul.queue').append('<li>'+ file +' <span>(<a href="#template-'+count+'">remove</a>)</span></li>').find('li:last').fadeIn(500).find('a').click(function(e){
					e.preventDefault();
					$($(this).attr('href')).remove();
					$(this).parents('li').fadeOut(500,function(){
						$(this).remove();
					});
				});
			});
			
		}
	},
	// contact form
	contact : {
		init : function(){
			Engine.errors = 0;
			$('#contact').submit(function(){
				Engine.validation.clear($('#contact'));
				Engine.validation.check($('#f-name'),Engine.validation.required,'Please enter your name');
				Engine.validation.check($('#f-email'),Engine.validation.email,'Please enter proper email address');
				Engine.validation.check($('#f-subject'),Engine.validation.required,'Please enter subject');
				Engine.validation.check($('#f-message'),Engine.validation.required,'Please enter your message');
				if(Engine.errors !== 0) return false;
				$(this).find('button').attr('disabled','disabled').blur().animate({ opacity: 0.4 }, 500);
			});
			
		}
	},
	// validation methods
	validation : {
		clear : function(container){
			Engine.errors = 0;
			container.find('p.error').remove();
		},
		check : function(field,rule,message){
			if(rule(field) === false){
				field.parent().after('<p class="error">'+ message +'</p>')
				Engine.errors++;
			}
		},
		required : function(field){
			return !! $(field).val();
		},
		email : function(field) {
			return /^[A-Z0-9._%+\-]+@[A-Z0-9.\-]+\.[A-Z]{2,6}$/i.test($(field).val());
		}
	},
	// testimonials rotate
	testimonials : {
		init : function(){
			if($('#testimonials').size() < 1) return false;
			
			container 	= $('#testimonials div.wrap-inner');
			count 		= container.find('div.item').size();
			
			if(count <= 1) return false;
			
			container.prepend('<ul class="index"><li class="prev"><a href="#prev">Previous testimonial</a></li><li class="next"><a href="#next">Next testimonial</a></li></ul>')
			container.find('ul.index').click(function(e){
				if(container.find('div.item:animated').size() > 0) return false;
				
				if(e.target.nodeName == 'A'){
					visible = container.find('div.item:visible');

					if(e.target.hash == '#prev'){
						if(visible.prev('div.item').size() > 0){
							var next = visible.prev('div.item');
						} else {
							var next = container.find('div.item:last');
						}
					} else if(e.target.hash == '#next') {
						if(visible.next('div.item').size() > 0){
							var next = visible.next('div.item');
						} else {
							var next = container.find('div.item:first');
						}
					}
					
					visible.fadeOut('slow',function(){
						next.fadeIn('slow');
					});
					//e.target.blur();
				}
				return false;
			});
		}
	},
	// go back link
	goBack : function(){
		$('span.go-back').each(function(){
			$(this).wrap('<a href="#back"></a>').click(function(){
				history.go(-1)
				return false;
			});
		});
	}
}

$(document).ready(function(){
	Engine.externalLinks();
	Engine.secureMails();
	Engine.answersToggle();
	Engine.deliciousAdd();
	Engine.calculator.init();
	Engine.order.init();
	Engine.order.printout();
	if(!$.browser.msie) Engine.order.upload();
	Engine.testimonials.init();
	Engine.contact.init();
	Engine.replaceHeaders();
	Engine.headerShadow();
	Engine.goBack();
});

document.write('<link rel="stylesheet" type="text/css" media="screen" href="styles/javascript.css" />');