// init page
window.addEvent('domready', function() {
	initInputs();
	initLabelFix();
	initGalleries();
	initLightboxes();
	initAnchorLinks();
	jcf.customForms.replaceAll();
});

// lightboxes init
function initLightboxes() {
	$$('a.open-popup').each(function(link){
		link.addEvent('click', function(){
			ModalBox.open(link);
			return !(ModalBox.lightbox || ModalBox.boxLoading);
		});
	});
}

// smooth anchor links init
function initAnchorLinks() {
	$$('a[data-role="anchor"]').each(function(obj){
		new SmoothAnchorLink({
			link: obj,
			animSpeed: 500
		})
	});
}

// clear inputs on focus
function initInputs() {
	$$('input[type="text"], input[type="password"], textarea').each(function(field){
		//field.setProperty('autocomplete','off');
		new PlaceholderInput({
			element:field,
			applyClearing: field.hasClass('place-holder'),
			wrapWithElement:false,
			showUntilTyping:false,
			getParentByClass:'row',
			placeholderAttr:'value'
		});
	});
}

// slideshow init
function initGalleries() {
	// testimonials gallery
	$$('div.testimonials').each(function(hold){
		new FadeGallery(hold, {
			slides: 'ul.gallery-list > li',
			activeClass: 'active',
			btnPrev: 'a.prev',
			btnNext: 'a.next',
			resizeHolder: true,
			autoRotation: true,
			switchTime: 8000,
			duration : 500
		});
	});
	// inner galleries
	$$('div.gallery').each(function(hold){
		new FadeGallery(hold, {
			slides: 'ul.gallery-list > li',
			activeClass: 'active',
			btnPrev: 'a.prev',
			btnNext: 'a.next',
			resizeHolder: true,
			autoRotation: true,
			switchTime: 8000,
			duration : 500
		});
	});
}

// label fix
function initLabelFix(set) {
	(set || $$('label')).each(function(label){
		if(!label.labelFixed) {
			label.labelFixed = new LabelFixer({
				label: label
			})
		}
	});
}

// order page class
OrderPage = new Class({
	Implements : [Options, Events],
	options: {
		// package settings
		form: null,
		maxBannerCount: 10,

		// display price element selectors
		dispBannerCount: 'span.banner-count',
		dispBannerPrice: 'span.banner-price',
		dispDesignPrice: 'span.design-price',
		dispMarkupPrice: 'span.markup-price',
		dispTotalPrice: 'span.total-price',
		dispEta: 'td.eta-string',
		radioParentClass: 'radio-selected'
	},
	initialize: function(options){
		this.setOptions(options);
		if(this.options.form) {
			this.findElements();
			this.refreshPackageRadios();
			this.refreshOrderRadios();
			this.initBannerArea();
			this.attachEvents();
			this.recalculate();
		}
	},
	findElements: function() {
		this.orderForm = this.options.form;
		this.orderTypeRadios = this.orderForm.getElements('input.order-type');
		this.packageRadios = this.orderForm.getElements('input.package-radio');

		// find display elements
		this.dispBannerCount = this.orderForm.getElement(this.options.dispBannerCount);
		this.dispBannerPrice = this.orderForm.getElement(this.options.dispBannerPrice);
		this.dispDesignPrice = this.orderForm.getElement(this.options.dispDesignPrice);
		this.dispMarkupPrice = this.orderForm.getElement(this.options.dispMarkupPrice);
		this.dispTotalPrice = this.orderForm.getElement(this.options.dispTotalPrice);
		this.dispEta = this.orderForm.getElement(this.options.dispEta);
	},
	attachEvents: function() {
		// recalculate on package change
		this.packageRadios.addEvent('click', function(){
			this.refreshPackageRadios();
			this.recalculate();
		}.bind(this));

		// recalculate on order type change
		this.orderTypeRadios.each(function(radio, index){
			// add handler
			radio.addEvent('click', function(){
				this.orderTypeChanged(index);
				this.refreshOrderRadios();
				this.refreshRowList();
				this.recalculate();

				// reposition order form
				if(typeof repositionOrderForm === 'function') {
					repositionOrderForm();
				}
			}.bind(this));

			// trigger order-type change event
			if(radio.checked) {
				radio.fireEvent('click');
			}
		}.bind(this));

		// if no order type buttons present
		if(!this.orderTypeRadios.length) {
			this.orderTypeChanged(0); // set "new order" type by default
		}
	},
	refreshOrderRadios: function() {
		this.orderTypeRadios.each(function(radio){
			var radioClass = radio.getProperty('data-packagename');
			if(radioClass) {
				if(radio.checked) {
					this.orderForm.addClass(radioClass);
					radio.getParent().addClass(this.options.radioParentClass);
				} else {
					this.orderForm.removeClass(radioClass);
					radio.getParent().removeClass(this.options.radioParentClass);
				}
			}
		}.bind(this));
	},
	refreshPackageRadios: function() {
		this.packageRadios.each(function(radio){
			var radioClass = radio.getProperty('data-packagename');
			if(radioClass) {
				if(radio.checked) {
					this.orderForm.addClass(radioClass);
					radio.getParent().addClass(this.options.radioParentClass);
				} else {
					this.orderForm.removeClass(radioClass);
					radio.getParent().removeClass(this.options.radioParentClass);
				}
			}
		}.bind(this));
	},
	orderTypeChanged: function(index) {
		this.currentOrderType = index;
		if(this.currentOrderType == 0) {
			// switching to "new order"
			this.formBanners.setMinRowsCount(2);
			if(this.formBanners.getAllRows().length < 2) {
				this.formBanners.addRow();
			}
			// enable all packages
			this.packageRadios.setProperty('disabled', false);
		} else {
			// switching to "existing order"
			this.formBanners.setMinRowsCount(1);
			if(this.formBanners.getAllRows().length < 1) {
				this.formBanners.addRow();
			}
			// disable all packages except "just banners"
			this.packageRadios.setProperty('disabled', true);
			this.packageRadios[0].setProperty('disabled', false).setProperty('checked', true).fireEvent('click');
		}
	},
	initBannerArea: function() {
		this.bannersArea = this.orderForm.getElement('div.banners-area');
		this.firstBannerPrice = parseFloat(this.bannersArea.getProperty('data-firstprice'));
		this.otherBannerPrice = parseFloat(this.bannersArea.getProperty('data-otherprice'));

		// banner rows cloning
		this.formBanners = new FormRowClone({
			holder: this.bannersArea,
			maxCloneCount: this.options.maxBannerCount
		}).addEvents({
			// handle node creation
			nodeCreated: function(){
				// refresh custom selects
				if(typeof initLabelFix === 'function') {
					initLabelFix(this.bannersArea.getElements('label'));
				}
				// refresh list object
				this.refreshRowList();
				this.recalculate();
			}.bind(this),

			// recalculate also when node removed
			nodeRemoved: function(){
				this.refreshRowList();
				this.recalculate();
			}.bind(this),

			// recalculate when something changed inside the row
			rowStateChanged: function(){
				this.recalculate();
			}.bind(this)
		});

		// create rows from array
		if(this.options.bannerData) {
			this.options.bannerData.each(function(rowSettings){
				this.setupRow(this.formBanners.addRow(), rowSettings);
			}.bind(this));
		}
		this.refreshRowList();
	},
	setupRow: function(row, settings) {
		// configure row with parameters
		row.getElement('input.banner-width').set('value', settings.width || 0);
		row.getElement('input.banner-height').set('value', settings.height || 0);
		row.getElement('input.chk-rounded').set('checked', !!settings.isRounded);
		row.getElement('input.chk-animated').set('checked', !!settings.isAnimated);
		row.getElement('input.chk-psd').set('checked', !!settings.isPsd);
	},
	refreshRowList: function() {
		this.rowList = [];
		this.formBanners.getAllRows().each(function(row, ind){
			// generate row object list
			this.rowList.push({
				isFirst: ind === 0,
				bannerRounded: row.getElement('input.chk-rounded'),
				bannerAnimated: row.getElement('input.chk-animated'),
				bannerPSD: row.getElement('input.chk-psd'),
				bannerPriceDisp: row.getElement('em.banner-row-total')
			});
		}.bind(this));
	},
	recalculate: function() {
		// calculate package price
		this.totalPrice = 0;
		this.designPrice = 0;
		this.markupPrice = 0;
		this.businessHours = 0;
		this.bannersCount = this.formBanners.getAllCount();
		var checkedItem = this.packageRadios.filter(':checked')[0];
		switch (checkedItem.getProperty('data-packagename')) {
			case 'design-only':
				//this.businessHours = 2*8; // add one 1..2 business days
				this.designPrice = parseFloat(checkedItem.getProperty('data-packageprice'));
				break;
			case 'design-with-markup':
				//this.businessHours = 3*8; // add one 2..3 business days
				var designOnlyRadio = this.packageRadios.filter('[data-packagename="design-only"]');
				this.designPrice = parseFloat(designOnlyRadio.getProperty('data-packageprice'));
				this.markupPrice = parseFloat(checkedItem.getProperty('data-packageprice')) - this.designPrice;
				break;
		}

		// calculate banner price
		this.bannerPrice = 0;
		this.rowList.each(function(row, ind){
			var basePrice = row.isFirst && this.currentOrderType == 0 ? this.firstBannerPrice : this.otherBannerPrice;
			if(row.bannerAnimated.checked) {
				basePrice += parseFloat(row.bannerAnimated.getProperty('data-price'));
			}
			if(row.bannerPSD.checked) {
				basePrice += parseFloat(row.bannerPSD.getProperty('data-price'));
			}
			row.bannerPriceDisp.set('text', basePrice);
			this.bannerPrice += basePrice;
		}.bind(this));
		this.dispBannerCount.set('text', this.bannersCount);
		this.dispBannerPrice.set('text', this.bannerPrice);

		// calculate eta
		this.businessHours += this.bannersCount * 4; // 4hr per banner
		this.dispEta.set('text', EtaHelper.convert(this.businessHours));

		// display results
		this.totalPrice = this.bannerPrice + this.designPrice + this.markupPrice;
		this.dispDesignPrice.set('text', this.designPrice);
		this.dispMarkupPrice.set('text', this.markupPrice);
		this.dispTotalPrice.set('text', this.totalPrice.toFixed(2));
	}
});

// ticket page class
TicketPage = new Class({
	Implements : [Options, Events],
	options: {
		// package settings
		form: null,
		maxBannerCount: 100
	},
	initialize: function(options){
		this.setOptions(options);
		if(this.options.form) {
			this.findElements();
			this.initBannerArea();
			this.attachEvents();
		}
	},
	findElements: function() {
		this.ticketForm = this.options.form;
	},
	attachEvents: function() {
		// misc event handlers
	},
	initBannerArea: function() {
		this.bannersArea = this.ticketForm.getElement('div.banners-area');
		this.firstBannerPrice = parseFloat(this.bannersArea.getProperty('data-firstprice'));
		this.otherBannerPrice = parseFloat(this.bannersArea.getProperty('data-otherprice'));

		// banner rows cloning
		this.formBanners = new FormRowClone({
			holder: this.bannersArea,
			maxCloneCount: this.options.maxBannerCount
		}).addEvents({
			// handle node creation
			nodeCreated: function(){
				// refresh custom selects
				if(typeof initLabelFix === 'function') {
					initLabelFix(this.bannersArea.getElements('label'));
				}
				if(typeof ModalBox !== 'undefined') {
					ModalBox.reposition();
				}

				// refresh list object
				this.refreshRowList();
				this.recalculate();
			}.bind(this),

			// recalculate also when node removed
			nodeRemoved: function(){
				if(typeof ModalBox !== 'undefined') {
					ModalBox.reposition();
				}

				this.refreshRowList();
				this.recalculate();
			}.bind(this),

			// recalculate when something changed inside the row
			rowStateChanged: function(){
				this.recalculate();
			}.bind(this)
		});

		// one row min
		this.formBanners.setMinRowsCount(1);

		// create rows from array
		if(this.options.bannerData) {
			this.options.bannerData.each(function(rowSettings){
				this.setupRow(this.formBanners.addRow(), rowSettings);
			}.bind(this));
		}
		this.refreshRowList();
	},
	setupRow: function(row, settings) {
		// configure row with parameters
		row.getElement('input.banner-width').set('value', settings.width || 0);
		row.getElement('input.banner-height').set('value', settings.height || 0);
		row.getElement('input.chk-rounded').set('checked', !!settings.isRounded);
		row.getElement('input.chk-animated').set('checked', !!settings.isAnimated);
		row.getElement('input.chk-psd').set('checked', !!settings.isPsd);
	},
	refreshRowList: function() {
		this.rowList = [];
		this.formBanners.getAllRows().each(function(row, ind){
			// generate row object list
			this.rowList.push({
				isFirst: ind === 0,
				bannerRounded: row.getElement('input.chk-rounded'),
				bannerAnimated: row.getElement('input.chk-animated'),
				bannerPSD: row.getElement('input.chk-psd'),
				bannerPriceDisp: row.getElement('em.banner-row-total')
			});
		}.bind(this));
	},
	recalculate: function() {
		// ticket page calculations:
		// calculate banner price
		this.bannerPrice = 0;
		this.rowList.each(function(row, ind){
			var basePrice = row.isFirst /* && this.currentOrderType == 0 */ ? this.firstBannerPrice : this.otherBannerPrice;
			if(row.bannerAnimated.checked) {
				basePrice += parseFloat(row.bannerAnimated.getProperty('data-price'));
			}
			if(row.bannerPSD.checked) {
				basePrice += parseFloat(row.bannerPSD.getProperty('data-price'));
			}
			row.bannerPriceDisp.set('text', basePrice);
			this.bannerPrice += basePrice;
		}.bind(this));
	}
});

// form row clone class
FormRowClone = new Class({
	Implements : [Options, Events],
	options: {
		holder: null,
		event: 'click',
		maxCloneCount: 5,
		renameFields: true,
		clonedClass: 'cloned',
		noRemoveClass: 'no-remove',
		maximumReachedClass: 'max-clones',
		holderSelector: 'div.rows-holder',
		cloneSelector: 'div.row.clone-example',
		btnRemoveSelector: 'a.close',
		btnAddSelector: '.btn-add a'
	},
	initialize: function(options){
		this.setOptions(options);
		if(this.options.holder) {
			this.findElements();
			this.initDefaultRows();
			this.refreshStateClasses();
		}
	},
	findElements: function(){
		this.guid = 0;
		this.minCount = 0;
		this.bannerArea = this.options.holder;
		this.rowsHolder = this.bannerArea.getElement(this.options.holderSelector);
		this.cloneExample = this.rowsHolder.getElement(this.options.cloneSelector);
		this.btnAddRow = this.bannerArea.getElement(this.options.btnAddSelector);
		this.btnAddRow.addEvent('click', this.addRow.bind(this));
		this.cloneExample.dispose();
	},
	initDefaultRows: function() {
		this.getAllRows().each(function(row){
			this.initRow(row, true);
		}.bind(this));
	},
	getCloneCount: function() {
		return this.getCloneRows().length;
	},
	getCloneRows: function() {
		return this.rowsHolder.getElements('.'+this.options.clonedClass);
	},
	getAllCount: function() {
		return this.getAllRows().length;
	},
	getAllRows: function() {
		return this.rowsHolder.getChildren().filter(function(item){
			// calculate only visible rows
			return item.offsetWidth > 0;
		});
	},
	setMinRowsCount: function(c) {
		if(typeof c === 'number') {
			this.minCount = c;
			this.refreshStateClasses();
		}
	},
	renameField: function(field, ind) {
		// change field name attribute
		if(field.name.indexOf('[') != -1) {
			field.name = field.name.substring(0, field.name.lastIndexOf('[')) + '['+ind+']';
		}
	},
	refreshFieldNames: function() {
		if(this.options.renameFields) {
			this.getAllRows().each(function(row, ind){
				row.getElements('input,textarea,select').each(function(input){
					this.renameField(input, ind);
				}.bind(this));
			}.bind(this));
		}
	},
	refreshStateClasses: function() {
		// toggle maximum class
		if(this.getCloneCount() === this.options.maxCloneCount) {
			this.bannerArea.addClass(this.options.maximumReachedClass);
		} else {
			this.bannerArea.removeClass(this.options.maximumReachedClass);
		}

		// disable removing of rows
		this.getAllRows().removeClass(this.options.noRemoveClass);
		if(this.getAllCount() === this.minCount) {
			this.getAllRows().addClass(this.options.noRemoveClass);
		}

		// rename fields
		this.refreshFieldNames();
	},
	addRow: function(e){
		if(this.getCloneCount() < this.options.maxCloneCount) {
			var newRow = this.cloneExample.clone(true,true).setStyles({display:'block'});
			newRow.addClass(this.options.clonedClass);
			this.initRow(newRow);
			this.rowsHolder.grab(newRow);

			// add class to holder to allow styling
			this.refreshStateClasses();

			// created event
			this.fireEvent('nodeCreated');
		}
		if(e && e.preventDefault) e.preventDefault();
		return newRow;
	},
	removeRow: function(row) {
		row.dispose();
		this.refreshStateClasses();
		this.fireEvent('nodeRemoved');
	},
	initRow: function(row, skipId) {
		// init close button
		row.getElements(this.options.btnRemoveSelector).addEvent('click', function(e){
			this.removeRow(row);
			e.preventDefault();
		}.bind(this));

		// init size selector
		row.getElements('div.size-select').each(function(box){
			new DimensionsSelector({
				holder:box
			});
		});

		// fix id in labels and inputs
		if(!skipId) {
			var rowSuffix = ++this.guid;
			row.getElements('label').each(function(label){
				if(label.htmlFor) {
					var input = row.getElement('input[id="'+label.htmlFor+'"]');
					if(input) {
						input.id += rowSuffix;
						label.htmlFor += rowSuffix;
					}
				}
			});
		}

		// handle row state change
		row.getElements('input[type="checkbox"]').addEvent('click', function(){
			// state changed event
			this.fireEvent('rowStateChanged');
		}.bind(this));
	}
});

// custom double select widget
DimensionsSelector = new Class({
	Implements : [Options, Events],
	options: {
		holder: null,
		customClass: 'custom',
		dropActiveClass: 'drop-active',
		openerSelector: 'a.selectButton',
		areaSelector: 'div.size-select-area',
		dropSelector: 'div.size-select-drop',
		fieldWidthSelector: 'input.banner-width',
		fieldHeightSelector: 'input.banner-height',
		event: 'click'
	},
	initialize: function(options){
		this.setOptions(options);
		if(this.options.holder) {
			this.findElements();
			this.refreshValues();
		}
	},
	findElements: function(){
		this.holder = this.options.holder;
		this.opener = this.holder.getElement(this.options.openerSelector);
		this.area = this.holder.getElement(this.options.areaSelector);
		this.drop = this.holder.getElement(this.options.dropSelector).setStyles({display:'none'}).dispose();
		this.opener.addEvent(this.options.event, this.toggleDrop.bind(this));

		// get inputs
		this.widthField = this.holder.getElement(this.options.fieldWidthSelector);
		this.heightField = this.holder.getElement(this.options.fieldHeightSelector);

		// drop items click handler
		this.optionList = this.drop.getElements('li');
		this.selectedIndex = this.optionList.length - 1;
		this.optionList.each(function(item, ind){
			item.addEvent('click', function(e){
				this.selectedIndex = ind;
				if(item.hasClass(this.options.customClass)) {
					this.emptyValues();
					this.widthField.focus();
				} else {
					var data = item.getElements('span');
					this.setValues(data[0].get('text'), data[1].get('text'));
				}
				this.hideDrop();
				if(e && e.preventDefault) e.preventDefault();
			}.bind(this));
		}.bind(this));

		// hide drop on field focus
		this.widthField.addEvent('focus', this.focusHandler.bind(this));
		this.heightField.addEvent('focus', this.focusHandler.bind(this));
		this.widthField.addEvent('blur', this.blurHandler.bind(this));
		this.heightField.addEvent('blur', this.blurHandler.bind(this));
		this.outsideClickHandler = this.outsideClickHandler.bind(this);
		this.repositionDrop = this.repositionDrop.bind(this);
		this.acceptOnlyNumbers(this.widthField);
		this.acceptOnlyNumbers(this.heightField);

		// save default|custom values
		setTimeout(function(){
			this.widthField.origValue = this.widthField.value;
			this.heightField.origValue = this.heightField.value;
		}.bind(this),100);
	},
	acceptOnlyNumbers: function(field) {
		field.addEvent('keyup',function(e){
			field.value = field.value.replace(/[^0-9]*/gi, '');
			e.preventDefault();
		});
	},
	focusHandler: function(e) {
		this.hideDrop();
		if(e.target.value.length) {
			e.target.origValue = e.target.value;
		}
		e.target.value = '';
	},
	blurHandler: function(e) {
		if(parseInt(e.target.value,10) === 0) {
			e.target.value = 1
		}
		if(!this.widthField.value) {
			this.widthField.value = this.widthField.origValue;
		} else {
			this.widthField.origValue = this.widthField.value;
		}
		if(!this.heightField.value) {
			this.heightField.value = this.heightField.origValue;
		} else {
			this.heightField.origValue = this.heightField.value;
		}
	},
	toggleDrop: function(e) {
		if(this.holder.hasClass(this.options.dropActiveClass)) {
			this.hideDrop();
		} else {
			this.showDrop();
		}
		if(e && e.preventDefault) e.preventDefault();
	},
	hideDrop: function() {
		this.holder.removeClass(this.options.dropActiveClass);
		this.drop.setStyles({display:'none'}).dispose();
		$(document).removeEvent('click', this.outsideClickHandler);
		$(window).removeEvent('resize', this.repositionDrop);
		$(window).removeEvent('scroll', this.repositionDrop);
	},
	repositionDrop: function() {
		var holderPosition = this.holder.getPosition();
		this.drop.setStyles({
			position: 'absolute',
			top: holderPosition.y + this.holder.getSize().y,
			left: holderPosition.x,
			width: this.holder.getSize().x
		});
	},
	showDrop: function() {
		$(document.body).grab(this.drop);
		this.holder.addClass(this.options.dropActiveClass);
		this.drop.setStyles({
			display:'block'
		});
		this.repositionDrop();
		$(document).addEvent('click', this.outsideClickHandler);
		$(window).addEvent('resize', this.repositionDrop);
		$(window).addEvent('scroll', this.repositionDrop);
	},
	outsideClickHandler: function(e) {
		var element = e.target;
		var hitFlag = false;
		while(element.parentNode) {
			if(element.parentNode == this.drop || element.parentNode == this.area) {
				hitFlag = true;
				break;
			}
			element = element.parentNode;
		}
		if(!hitFlag) {
			this.hideDrop();
		}
	},
	emptyValues: function() {
		this.setValues('','');
	},
	setValues: function(x,y) {
		if(typeof x === 'string' || typeof x === 'number') {
			this.widthField.set('value',x);
			if(this.widthField.value.length) this.widthField.origValue = this.widthField.value;
		}
		if(typeof y === 'string' || typeof y === 'number') {
			this.heightField.set('value',y);
			if(this.heightField.value.length) this.heightField.origValue = this.heightField.value;
		}
	},
	refreshValues: function() {
		if(!this.optionList[this.selectedIndex].hasClass(this.options.customClass)) {
			this.optionList[this.selectedIndex].fireEvent('click');
		}
	}
});

// smooth anchor links class
SmoothAnchorLink = new Class({
	Implements : [Options, Events],
	options: {
		link: null,
		animSpeed: 400,
		event: 'click'
	},
	initialize: function(options){
		this.setOptions(options);
		if(this.options.link) {
			this.findElements();
		}
	},
	findElements: function(){
		this.link = this.options.link;
		this.target = $(this.link.href.substr(this.link.href.indexOf('#') + 1));
		if(this.target) {
			this.link.addEvent(this.options.event, this.actionHandler.bind(this));
		}
	},
	actionHandler: function(e) {
		this.smoothScrollTo(this.target.getPosition().y);
		e.preventDefault();
	},
	smoothScrollTo: function(offset) {
		new Fx.Scroll(document.body, {
			wheelStops: true,
			duration: this.options.animSpeed,
			offset: {
				y: offset
			}
		}).toTop();
	}
});

// ETA converter utility module
EtaHelper = {
	monthNames: ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'],
	convert: function(hours) {
		var startDate = new Date();
		var businessDays = Math.ceil(hours / 8);
		var step = 0;
		while (step < businessDays) {
			do {
				startDate.setDate(startDate.getDate()+1);
			} while(startDate.getDay() === 0 || startDate.getDay() === 6);
			step++;
		}
		return this.printDate(startDate, businessDays);
	},
	getDaySuffix: function(day) {
		switch (day % 10) {
			case 1: return 'st';
			case 2: return 'nd';
			case 3: return 'rd';
			default: return 'th';
		}
	},
	getBusinessDaysText: function(days) {
		return ' business day' + (days > 1 ? 's' : '');
	},
	printDate: function(date,days) {
		return this.monthNames[date.getMonth()] + ' ' + date.getDate() + ', ' + days + this.getBusinessDaysText();
	}
};

// popups module
ModalBox = {
	options: {
		zIndex: 1000,
		animSpeed: 350,
		faderOpacity: 0.85,
		faderBackground: '#616a73',
		faderId: 'lightbox-overlay',
		actionsClass: 'popup-prepared',
		closeButtons: '> a.close, a.cancel',
		imageLightboxStructure: '<div class="lightbox-area"><a href="#" class="close" title="close">x</a><div class="lightbox"></div></div>',
		imageLightboxHolder: '.lightbox'
	},
	init: function() {
		window.addEvent('domready', function(){
			this.createElements();
			this.setupHandlers();
		}.bind(this));
		return this;
	},
	createElements: function() {
		// get global elements
		this.body = $(document.body);
		this.page = $$('div')[0];
		this.minWidth = parseInt($(document.body).getStyle('minWidth'));

		// create fader
		this.fader = new Element('div', {
			id: this.options.faderId,
			styles: {
				backgroundColor: this.options.faderBackground,
				opacity:this.options.faderOpacity,
				zIndex:this.options.zIndex,
				position:'absolute',
				overflow:'hidden',
				display:'none',
				opacity:0,
				top:0,
				left:0
			},
			events: {
				click: this.close.bind(this)
			}
		});
		this.fader.setStyles();
		this.body.grab(this.fader);

		// IE6 iframe fix
		if(/MSIE 6/.test(navigator.userAgent)) {
			this.ieFrameFix = new Element('iframe', {
				src: 'javascript:false',
				frameBorder: 0,
				scrolling: 'no',
				width: '100%',
				height: '100%',
				styles: {
					opacity:0,
					zIndex:-1
				}
			});
			this.fader.grab(this.ieFrameFix);
		}
	},
	setupHandlers: function() {
		window.addEvent('resize', this.reposition.bind(this));
		window.addEvent('scroll', this.reposition.bind(this));
		document.addEvent('keydown', function(e) {
			if (e.key === 'esc') {
				this.close();
			}
		}.bind(this));
	},
	initPopupActions: function(popup) {
		if(!popup.hasClass(this.options.actionsClass)) {
			popup.addClass(this.options.actionsClass);
			popup.getElements(this.options.closeButtons).addEvent('click', this.close.bind(this));
		}
	},
	toggleFader: function(state, callback) {
		var faderFx = new Fx.Morph(this.fader, {duration: this.options.animSpeed, onComplete:function(){
			if(!state) {
				this.fader.setStyles({display:'none'});
			}
			if(typeof callback === 'function') {
				callback.call(this);
			}
		}.bind(this)});
		if(state) {
			this.reposition(true);
			this.fader.setStyles({display:'block'});
		}
		faderFx.start({opacity:state ? this.options.faderOpacity : 0});
	},
	toggleModal: function(state, callback) {
		var popupFx = new Fx.Morph(this.lightbox, {duration: this.options.animSpeed, onComplete:function(){
			if(!state) {
				this.lightbox.setStyles({display:'none'});
			}
			if(typeof callback === 'function') {
				callback.call(this);
			}
		}.bind(this)});
		if(state) {
			this.lightbox.setStyles({display:'block',opacity:0});
			this.reposition();
		}
		popupFx.start({opacity:state ? 1 : 0});
	},
	toggleState: function(state) {
		if(this.lightbox) {
			if(state) {
				this.toggleFader(true, function() {
					this.toggleModal(true, function() {
						// global lightbox events
						window.fireEvent('modalshow');
					});
				});
			} else {
				this.toggleModal(false, function() {
					this.toggleFader(false, function() {
						// global lightbox events
						if(this.boxLoading) {
							this.lightbox.dispose();
						}
						this.lightbox = null;
						this.boxLoading = false;
						this.scrollFlag = false;
						window.fireEvent('modalhide');
					});
				});
			}
		}
	},
	reposition: function(faderOnly) {
		if(this.lightbox) {
			this.fader.setStyles({display:'none'});
			var pageWidth = this.getPageWidth(), windowWidth = Math.max(this.minWidth, this.getWindowWidth());
			var pageHeight = this.getPageHeight(), windowHeight = this.getWindowHeight();
			var lightboxWidth = this.lightbox.getSize().x;
			var lightboxHeight = this.lightbox.getSize().y;

			// fader size
			this.fader.setStyles({
				display: 'block',
				width: pageWidth,
				height: pageHeight
			});
			if(faderOnly) return;

			// lightbox fits in window
			if(lightboxHeight < windowHeight) {
				this.scrollFlag = false;
				this.lightbox.setStyles({
					position: 'fixed',
					zIndex: this.options.zIndex+1,
					top: Math.max(0, (windowHeight - lightboxHeight) / 2),
					left: (windowWidth - lightboxWidth) / 2
				});
				if(windowWidth <= this.minWidth) {
					this.lightbox.setStyles({
						position: 'absolute'
					});
				}
			} else {
				this.lightbox.setStyles({
					position: 'absolute',
					zIndex: this.options.zIndex+1,
					left: (windowWidth - lightboxWidth) / 2
				});
				if(!this.scrollFlag) {
					this.lightbox.setStyles({
						top: (window.pageYOffset || document.documentElement.scrollTop)
					});
				}
				this.scrollFlag = true;
			}
		}
	},
	getPageWidth: function() {
		return Math.max(
			//Math.max(document.documentElement.offsetWidth, document.documentElement.scrollWidth),
			Math.max(document.body.offsetWidth, document.body.scrollWidth)
		);
	},
	getPageHeight: function() {
		return Math.max(
			Math.max(document.documentElement.offsetHeight, document.documentElement.scrollHeight),
			Math.max(document.body.offsetHeight, document.body.scrollHeight)
		);
	},
	getWindowWidth: function() {
		return typeof window.innerWidth === 'number' ? window.innerWidth : document.documentElement.clientWidth;
	},
	getWindowHeight: function() {
		return typeof window.innerHeight === 'number' ? window.innerHeight : document.documentElement.clientHeight;
	},
	prepareLightbox: function(link, callback) {
		var modalDiv, linkHref;
		if(typeof link === 'string') {
			linkHref = link;
		} else {
			linkHref = link.getProperty('data-lightbox') || link.href;
			linkHref = linkHref.substr(linkHref.indexOf('#') + 1);
		}
		// image processing
		if(linkHref.indexOf('.') > 0) {
			var tmpDiv = new Element('div', {html: this.options.imageLightboxStructure}).getChildren()[0];
			var tmpImg = new Element('img', {src: linkHref});
			var tmpHold = tmpDiv.getElement(this.options.imageLightboxHolder);
			$(document.body).grab(tmpDiv);
			tmpHold.grab(tmpImg);

			// wait for image load
			this.boxLoading = true;
			if(tmpImg.complete) {
				if(typeof callback === 'function') {
					callback.call(this, tmpDiv);
				}
		} else {
				tmpImg.onload = function() {
					if(typeof callback === 'function') {
						callback.call(this, tmpDiv);
		}
				}.bind(this)
			}
		}
		// inline div processing
		else {
			modalDiv = $(linkHref);
			if(typeof callback === 'function') {
				callback.call(this, modalDiv);
			}
		}
	},
	openModalBox: function(link) {
		this.prepareLightbox(link, function(div) {
			this.lightbox = div;
		if(this.lightbox) {
			this.initPopupActions(this.lightbox);
			this.toggleState(true);
		}
		});
	},
	open: function(link) {
		// hide active popup
		if(this.lightbox) {
			this.toggleModal(false, function(){
				this.openModalBox(link);
			})
		} else {
			this.openModalBox(link);
		}
	},
	close: function(e) {
		this.toggleState(false);
		if(e && e.preventDefault) {
			e.preventDefault();
		}
	}
}.init();

// smooth horizontal slider class
SmoothSlider = new Class({
	Implements : [Options, Events],
	options: {
		min: 0,
		max: 1,
		holder: null,
		handleHolder: 'div.mask',
		handle: 'a',
		btnDec: 'a.dec',
		btnInc: 'a.inc',
		animSpeed : 200,
		event: 'click'
	},
	initialize: function(options){
		this.setOptions(options);
		if(this.options.holder) {
			this.findElements();
			this.attachEvents();
		}
	},
	findElements: function(){
		// get elements
		this.page = $(document.body);
		this.handleHolder = this.options.holder.getElement(this.options.handleHolder);
		this.handle = this.handleHolder.getElement(this.options.handle);
		this.btnDec = this.options.holder.getElements(this.options.btnDec);
		this.btnInc = this.options.holder.getElements(this.options.btnInc);

		// init variables
		this.recalculateVariables();
	},
	recalculateVariables: function() {
		this.currentIndex = 0;
		this.value = this.options.value;
		this.stepCount = this.options.max - this.options.min;
		this.holderWidth = this.handleHolder.getSize().x;
		this.handleWidth = this.handle.getSize().x;
		this.stepWidth = Math.floor((this.holderWidth - this.handleWidth) / this.stepCount);
		this.handle.setStyles({left: (this.value - this.options.min) * this.stepWidth });
	},
	attachEvents: function(){
		this.btnDec.addEvent(this.options.event, this.decrementValue.bind(this));
		this.btnInc.addEvent(this.options.event, this.incrementValue.bind(this));
		this.initDraggableSlider();
	},
	initDraggableSlider: function() {
		var instance = this, blockOffset, handleOffset, innerOffset;

		// draggable handlers
		function dragStart(e) {
			instance.cancelHandleAnimation();
			blockOffset = instance.handleHolder.getPosition().x;
			handleOffset = instance.handle.getPosition().x;
			innerOffset = e.page.x - handleOffset;

			instance.page.addEvent('mousemove', dragMove);
			instance.page.addEvent('mouseup', dragEnd);
			return false;
		}
		function dragMove(e) {
			// control position
			var offset = e.page.x - blockOffset - innerOffset;
			if(offset < 0) {
				offset = 0;
			} else if(offset > instance.holderWidth - instance.handleWidth) {
				offset = instance.holderWidth - instance.handleWidth;
			}
			instance.handle.setStyles({left: offset});

			// get position index
			checkPosition(offset)
			return false;
		}
		function dragEnd(e) {
			instance.animateHandlePosition(instance.currentIndex);
			instance.page.removeEvent('mousemove', dragMove);
			instance.page.removeEvent('mouseup', dragEnd);
		}
		function clickMove(e) {
			checkPosition(e.page.x - instance.handleHolder.getPosition().x)
			instance.animateHandlePosition(instance.currentIndex);
		}
		function checkPosition(offset) {
			var positionIndex = Math.round(offset / instance.stepWidth);
			if(positionIndex !== instance.currentIndex) {
				instance.currentIndex = positionIndex;
				instance.setValue(instance.currentIndex + instance.options.min);
			}
		}

		// drag start handler
		instance.handleHolder.addEvent('mousedown', clickMove);
		instance.handle.addEvent('mousedown', dragStart);
		instance.handle.addEvent('click', function(){return false});
	},
	cancelHandleAnimation: function() {
		if(this.oldFx && typeof this.oldFx.cancel === 'function') {
			this.oldFx.cancel();
		}
	},
	animateHandlePosition: function(ind) {
		// restore nearest slider position
		this.cancelHandleAnimation();
		this.oldFx = new Fx.Morph(this.handle, {
			link:'ignore',
			duration: this.options.animSpeed,
			transition: Fx.Transitions.linear,
			onComplete:function(){
				//
			}
		}).start({left: (typeof ind === 'number' ? ind : this.currentIndex ) * this.stepWidth});
	},
	decrementValue: function() {
		if(this.value > this.options.min) {
			this.setValue(this.value - 1);
			this.animateHandlePosition();
		}
		return false;
	},
	incrementValue: function() {
		if(this.value < this.options.max) {
			this.setValue(this.value + 1);
			this.animateHandlePosition();
		}
		return false;
	},
	setValue: function(v) {
		// update values
		this.value = v;
		this.currentIndex = this.value - this.options.min;
		if(this.currentIndex < 0) {
			this.currentIndex = 0;
		} else if(this.currentIndex > this.stepCount) {
			this.currentIndex = this.stepCount;
		}

		// onchange callback
		if(typeof this.options.valueChanged === 'function') {
			this.options.valueChanged(this.value);
		}
	}
});

// fade gallery class
FadeGallery = new Class({
	Implements : [Options, Events],
	options: {
		pagerLinks: 'ul.pagerlinks li',
		slides: 'ul.slidelist li',
		activeClass: 'active',
		btnPrev: 'a.btn-prev',
		btnNext: 'a.btn-next',
		autoRotation: false,
		resizeHolder: false,
		switchTime: 3000,
		duration : 500,
		event: 'click'
	},

	// create class
	initialize: function(element, options){
		this.setOptions(options);

		// read options
		this.slideset = element.getElements(this.options.slides);
		this.pagerLinks = element.getElements(this.options.pagerLinks);
		this.btnPrev = element.getElements(this.options.btnPrev);
		this.btnNext = element.getElements(this.options.btnNext);
		this.autoRotation = this.options.autoRotation;
		this.activeClass = this.options.activeClass;
		this.switchTime = this.options.switchTime;
		this.slidesCount = this.slideset.length;

		// slides
		if (this.slidesCount < 2) return;
		this.duration = this.options.duration;
		this.timer = false;
		this.oldIndex = 0;
		this.currentIndex = 0;

		// gallery init
		this.slideset.each(function(slide, ind){
			if(ind != this.currentIndex) slide.removeClass(this.activeClass).setStyles({display:'none',opacity:0});
			else slide.addClass(this.activeClass).setStyles({display:'block',opacity:1});
		}.bind(this));
		if(this.options.resizeHolder) {
			this.slidesHolder = $(this.slideset[this.currentIndex].parentNode);
			this.slidesHolder.setStyles({height: this.slideset[this.currentIndex].getSize().y});
		}

		// init controls
		if(this.pagerLinks.length) {
			this.pagerLinks.each(function(item,ind){
				item.addEvent(this.options.event, function(){
					this.numSlide(ind);
					return false;
				}.bind(this));
			}.bind(this));
		}
		this.btnPrev.addEvent(this.options.event, this.prevSlide.bind(this));
		this.btnNext.addEvent(this.options.event, this.nextSlide.bind(this));

		// start autoslide
		if (this.options.autoRotation) {
			this.autoSlide();
		}
	},
	refreshPagination:function(){
		var _this = this;
		if(this.pagerLinks.length) {
			this.pagerLinks.each(function(item,ind){
				if(ind == _this.currentIndex) item.addClass(_this.activeClass);
				else item.removeClass(_this.activeClass)
			});
		}
	},
	numSlide: function(ind){
		if(!this.animating && this.currentIndex != ind) {
			this.oldIndex = this.currentIndex;
			this.currentIndex = ind;
			this.switchSlide();
		}
	},
	nextSlide: function(){
		if(!this.animating) {
			this.oldIndex = this.currentIndex;
			if(this.currentIndex < this.slidesCount-1) this.currentIndex++;
			else this.currentIndex = 0;
			this.switchSlide();
		}
		return false;
	},
	prevSlide: function(){
		if(!this.animating) {
			this.oldIndex = this.currentIndex;
			this.currentIndex--;
			if (this.currentIndex < 0) this.currentIndex = this.slidesCount-1;
			this.switchSlide();
		}
		return false;
	},
	switchSlide:function(){
		this.animating = true;
		var oldSlide = this.slideset[this.oldIndex].removeClass(this.activeClass).setStyles({opacity:1,display:'block'});
		var newSlide = this.slideset[this.currentIndex].addClass(this.activeClass).setStyles({opacity:0,display:'block'});

		// fade elements
		var fxFadeOut = new Fx.Morph(oldSlide, {duration: this.duration, onComplete:function(){
			oldSlide.setStyles({display:'none'});
			this.animating = false;
		}.bind(this)});
		var fxFadeIn = new Fx.Morph(newSlide, {duration: this.duration});
		fxFadeOut.start({opacity:0});
		fxFadeIn.start({opacity:1});

		// resize holder
		if(this.options.resizeHolder) {
			new Fx.Morph(this.slidesHolder, {duration: this.duration}).start({height:newSlide.getSize().y});
		}

		this.autoSlide();
		this.refreshPagination();
	},
	autoSlide: function(){
		if(this.options.autoRotation) {
			var _this = this;
			if(this.timer) clearTimeout(this.timer);
			this.timer = setTimeout(function(){_this.nextSlide()}, this.switchTime);
		}
	}
});

// mobile browsers detect, add stylesheet for mobile devices
browserPlatform = {
	platforms: [
		{ uaString:'Android', cssFile:'android.css' }, // Android
		{ uaString:['BlackBerry','/6.0','mobi'], cssFile:'blackberry6.css' }, // Blackberry 6
		{ uaString:['safari','mobi'], cssFile:'safari.css' } // webkit browsers
	],
	options: {
		cssPath:'css/',
		mobileCSS:'allmobile.css'
	},
	init:function(){
		this.checkMobile();
		this.parsePlatforms();
		return this;
	},
	checkMobile: function() {
		if(this.uaMatch('mobi') || this.uaMatch('midp') || this.uaMatch('ppc') || this.uaMatch('webos')) {
			this.attachStyles({cssFile:this.options.mobileCSS});
		}
	},
	parsePlatforms: function() {
		for(var i = 0; i < this.platforms.length; i++) {
			if(typeof this.platforms[i].uaString === 'string') {
				if(this.uaMatch(this.platforms[i].uaString)) {
					this.attachStyles(this.platforms[i]);
					break;
				}
			} else {
				for(var j = 0, allMatch = true; j < this.platforms[i].uaString.length; j++) {
					if(!this.uaMatch(this.platforms[i].uaString[j])) {
						allMatch = false;
					}
				}
				if(allMatch) {
					this.attachStyles(this.platforms[i]);
					break;
				}
			}
		}
	},
	attachStyles: function(platform) {
		var head = document.getElementsByTagName('head')[0], fragment;
		var cssText = '<link rel="stylesheet" href="' + this.options.cssPath + platform.cssFile + '" type="text/css"/>';
		var miscText = platform.miscHead;
		if(platform.cssFile) {
			if(document.body) {
				fragment = document.createElement('div');
				fragment.innerHTML = cssText;
				head.appendChild(fragment.childNodes[0]);
			} else {
				document.write(cssText);
			}
		}
	},
	uaMatch:function(str) {
		if(!this.ua) {
			this.ua = navigator.userAgent.toLowerCase();
		}
		return this.ua.indexOf(str.toLowerCase()) != -1;
	}
}.init();

// mobile devices laber for fix
LabelFixer = new Class({
	Implements : [Options, Events],
	options: {
		label: null,
		triggerClick: true,
		event: 'touchstart'
	},
	initialize: function(options){
		this.setOptions(options);
		if(this.options.label && this.options.label.htmlFor) {
			this.label = this.options.label;
			this.input = $(this.label.htmlFor);
			if(this.input) {
				this.fixBehaviour();
			}
		}
	},
	fixBehaviour: function() {
		this.inputType = (this.input.type ? this.input.type : this.input.tagName).toLowerCase();
		this.label.addEvent(this.options.event, this.toggleElement.bind(this));
	},
	toggleElement: function(e) {
		if(!this.input.disabled) {
			switch(this.inputType) {
				case 'radio':
					this.input.checked = true;
					break;
				case 'checkbox':
					this.input.checked = !this.input.checked;
					break;
				default:
					this.input.focus();
			}
			if(this.options.triggerClick) {
				this.input.fireEvent('click');
			}
		}
		e.preventDefault();
	}
});

// input type placeholder class
;(function(){
	PlaceholderInput = function() {
		this.options = {
			element:null,
			showUntilTyping:false,
			wrapWithElement:false,
			getParentByClass:false,
			placeholderAttr:'value',
			inputFocusClass:'focus',
			inputActiveClass:'text-active',
			parentFocusClass:'parent-focus',
			parentActiveClass:'parent-active',
			labelFocusClass:'label-focus',
			labelActiveClass:'label-active',
			fakeElementClass:'input-placeholder-text'
		}
		this.init.apply(this,arguments);
	}
	PlaceholderInput.convertToArray = function(collection) {
		var arr = [];
		for (var i = 0, ref = arr.length = collection.length; i < ref; i++) {
		 arr[i] = collection[i];
		}
		return arr;
	}
	PlaceholderInput.getInputType = function(input) {
		return (input.type ? input.type : input.tagName).toLowerCase();
	}
	PlaceholderInput.prototype = {
		init: function(opt) {
			this.setOptions(opt);
			this.options.applyClearing = this.options.applyClearing || this.elementType == 'password';
			if(this.element && this.element.PlaceholderInst) {
				this.element.PlaceholderInst.refreshClasses();
			} else {
				this.element.PlaceholderInst = this;
				if(this.elementType == 'text' || this.elementType == 'password' || this.elementType == 'textarea') {
					this.initElements();
					this.attachEvents();
					this.refreshClasses();
				}
			}
		},
		setOptions: function(opt) {
			for(var p in opt) {
				if(opt.hasOwnProperty(p)) {
					this.options[p] = opt[p];
				}
			}
			if(this.options.element) {
				this.element = this.options.element;
				this.elementType = PlaceholderInput.getInputType(this.element);
				this.wrapWithElement = (this.elementType === 'password' || this.options.showUntilTyping ? true : this.options.wrapWithElement);
				this.setOrigValue( this.options.placeholderAttr == 'value' ? this.element.defaultValue : this.element.getAttribute(this.options.placeholderAttr) );
			}
		},
		setOrigValue: function(value) {
			this.origValue = value;
		},
		initElements: function() {
			// create fake element if needed
			if(this.wrapWithElement) {
				this.element.value = '';
				this.element.removeAttribute(this.options.placeholderAttr);
				this.fakeElement = document.createElement('span');
				this.fakeElement.className = this.options.fakeElementClass;
				this.fakeElement.innerHTML += this.origValue;
				this.fakeElement.style.color = getStyle(this.element, 'color');
				this.fakeElement.style.position = 'absolute';
				this.element.parentNode.insertBefore(this.fakeElement, this.element);
			}
			// get input label
			if(this.element.id) {
				this.labels = document.getElementsByTagName('label');
				for(var i = 0; i < this.labels.length; i++) {
					if(this.labels[i].htmlFor === this.element.id) {
						this.labelFor = this.labels[i];
						break;
					}
				}
			}
			// get parent node (or parentNode by className)
			this.elementParent = this.element.parentNode;
			if(typeof this.options.getParentByClass === 'string') {
				var el = this.element;
				while(el.parentNode) {
					if(hasClass(el.parentNode, this.options.getParentByClass)) {
						this.elementParent = el.parentNode;
						break;
					} else {
						el = el.parentNode;
					}
				}
			}
		},
		attachEvents: function() {
			this.element.onfocus = bindScope(this.focusHandler, this);
			this.element.onblur = bindScope(this.blurHandler, this);
			if(this.options.showUntilTyping) {
				this.element.onkeydown = bindScope(this.typingHandler, this);
				this.element.onpaste = bindScope(this.typingHandler, this);
			}
			if(this.wrapWithElement) this.fakeElement.onclick = bindScope(this.focusSetter, this);
		},
		togglePlaceholderText: function(state) {
			if(this.wrapWithElement) {
				this.fakeElement.style.display = state ? '' : 'none';
			} else {
				this.element.value = state ? this.origValue : '';
			}
		},
		focusSetter: function() {
			this.element.focus();
		},
		focusHandler: function() {
			this.focused = true;
			if(this.options.applyClearing) {
				if(!this.element.value.length || this.element.value === this.origValue) {
					if(!this.options.showUntilTyping) {
						this.togglePlaceholderText(false);
					}
				}
			}
			this.refreshClasses();
		},
		blurHandler: function() {
			this.focused = false;
			if(this.options.applyClearing) {
				if(!this.element.value.length || this.element.value === this.origValue) {
					this.togglePlaceholderText(true);
				}
			}
			this.refreshClasses();
		},
		typingHandler: function() {
			setTimeout(bindScope(function(){
				if(this.element.value.length) {
					this.togglePlaceholderText(false);
					this.refreshClasses();
				}
			},this), 10);
		},
		refreshClasses: function() {
			this.textActive = this.focused || (this.element.value.length && this.element.value !== this.origValue);
			this.setStateClass(this.element, this.options.inputFocusClass,this.focused);
			this.setStateClass(this.elementParent, this.options.parentFocusClass,this.focused);
			this.setStateClass(this.labelFor, this.options.labelFocusClass,this.focused);
			this.setStateClass(this.element, this.options.inputActiveClass, this.textActive);
			this.setStateClass(this.elementParent, this.options.parentActiveClass, this.textActive);
			this.setStateClass(this.labelFor, this.options.labelActiveClass, this.textActive);
		},
		setStateClass: function(el,cls,state) {
			if(!el) return; else if(state) addClass(el,cls); else removeClass(el,cls);
		}
	}

	// utility functions
	function hasClass(el,cls) {
		return el.className ? el.className.match(new RegExp('(\\s|^)'+cls+'(\\s|$)')) : false;
	}
	function addClass(el,cls) {
		if (!hasClass(el,cls)) el.className += " "+cls;
	}
	function removeClass(el,cls) {
		if (hasClass(el,cls)) {el.className=el.className.replace(new RegExp('(\\s|^)'+cls+'(\\s|$)'),' ');}
	}
	function bindScope(f, scope) {
		return function() {return f.apply(scope, arguments)}
	}
	function getStyle(el, prop) {
		if (document.defaultView && document.defaultView.getComputedStyle) {
			return document.defaultView.getComputedStyle(el, null)[prop];
		} else if (el.currentStyle) {
			return el.currentStyle[prop];
		} else {
			return el.style[prop];
		}
	}
}());

// browser detect script
browserDetect = {
	matchGroups: [
		[
			{uaString:'win', className:'win'},
			{uaString:'mac', className:'mac'},
			{uaString:['linux','x11'], className:'linux'}
		],
		[
			{uaString:'msie', className:'trident'},
			{uaString:'applewebkit', className:'webkit'},
			{uaString:'gecko', className:'gecko'},
			{uaString:'opera', className:'presto'}
		],
		[
			{uaString:'msie 9.0', className:'ie9'},
			{uaString:'msie 8.0', className:'ie8'},
			{uaString:'msie 7.0', className:'ie7'},
			{uaString:'msie 6.0', className:'ie6'},
			{uaString:'firefox/2', className:'ff2'},
			{uaString:'firefox/3', className:'ff3'},
			{uaString:'firefox/4', className:'ff4'},
			{uaString:['opera','version/11'], className:'opera11'},
			{uaString:['opera','version/10'], className:'opera10'},
			{uaString:'opera/9', className:'opera9'},
			{uaString:['safari','version/3'], className:'safari3'},
			{uaString:['safari','version/4'], className:'safari4'},
			{uaString:['safari','version/5'], className:'safari5'},
			{uaString:'chrome', className:'chrome'},
			{uaString:'safari', className:'safari2'},
			{uaString:'unknown', className:'unknown'}
		]
	],
	init: function() {
		this.detect();
		return this;
	},
	addClass: function(className) {
		this.pageHolder = document.documentElement;
		document.documentElement.className += ' '+className;
	},
	detect: function() {
		for(var i = 0, curGroup; i < this.matchGroups.length; i++) {
			curGroup = this.matchGroups[i];
			for(var j = 0, curItem; j < curGroup.length; j++) {
				curItem = curGroup[j];
				if(typeof curItem.uaString === 'string') {
					if(this.uaMatch(curItem.uaString)) {
						this.addClass(curItem.className);
						break;
					}
				} else {
					for(var k = 0, allMatch = true; k < curItem.uaString.length; k++) {
						if(!this.uaMatch(curItem.uaString[k])) {
							allMatch = false;
							break;
						}
					}
					if(allMatch) {
						this.addClass(curItem.className);
						break;
					}
				}
			}
		}
	},
	uaMatch: function(s) {
		if(!this.ua) {
			this.ua = navigator.userAgent.toLowerCase();
		}
		return this.ua.indexOf(s) != -1;
	}
}.init();

/*
 * JavaScript Custom Forms 1.3.5
 */
jcf = {
	// global options
	modules: {},
	plugins: {},
	baseOptions: {
		labelActiveClass: 'jcf-label-active',
		hiddenClass:'jcf-hidden',
		focusClass:'jcf-focus',
		wrapperTag: 'div'
	},
	// replacer function
	customForms: {
		setOptions: function(obj) {
			for(var p in obj) {
				if(obj.hasOwnProperty(p) && typeof obj[p] === 'object') {
					jcf.lib.extend(jcf.modules[p].prototype.defaultOptions, obj[p]);
				}
			}
		},
		replaceAll: function() {
			for(var k in jcf.modules) {
				var els = jcf.lib.queryBySelector(jcf.modules[k].prototype.selector);
				for(var i = 0; i<els.length; i++) {
					if(els[i].jcf) {
						// refresh form element state
						els[i].jcf.refreshState();
					} else {
						// replace form element
						if(jcf.modules[k].prototype.checkElement(els[i])) {
							new jcf.modules[k]({
								replaces:els[i]
							});
						}
					}
				}
			}
		},
		refreshAll: function() {
			for(var k in jcf.modules) {
				var els = jcf.lib.queryBySelector(jcf.modules[k].prototype.selector);
				for(var i = 0; i<els.length; i++) {
					if(els[i].jcf) {
						// refresh form element state
						els[i].jcf.refreshState();
					}
				}
			}
		},
		refreshElement: function(obj) {
			if(obj && obj.jcf) {
				obj.jcf.refreshState();
			}
		},
		destroyAll: function() {
			for(var k in jcf.modules) {
				var els = jcf.lib.queryBySelector(jcf.modules[k].prototype.selector);
				for(var i = 0; i<els.length; i++) {
					if(els[i].jcf) {
						els[i].jcf.destroy();
					}
				}
			}
		}
	},
	// detect device type
	isTouchDevice: (function() {
		try {
			document.createEvent('TouchEvent');
			return true;
		} catch (e) {
			return false;
		}
	}()),
	// define base module
	setBaseModule: function(obj) {
		jcf.customControl = function(opt){
			this.options = jcf.lib.extend({}, jcf.baseOptions, this.defaultOptions, opt);
			this.init();
		}
		for(var p in obj) {
			jcf.customControl.prototype[p] = obj[p];
		}
	},
	// add module to jcf.modules
	addModule: function(obj) {
		if(obj.name){
			// create new module proto class
			jcf.modules[obj.name] = function(){
				jcf.modules[obj.name].superclass.constructor.apply(this, arguments);
			}
			jcf.lib.inherit(jcf.modules[obj.name], jcf.customControl);
			for(var p in obj) {
				jcf.modules[obj.name].prototype[p] = obj[p]
			}
			// on create module
			jcf.modules[obj.name].prototype.onCreateModule();
			// make callback for exciting modules
			for(var mod in jcf.modules) {
				if(jcf.modules[mod] != jcf.modules[obj.name]) {
					jcf.modules[mod].prototype.onModuleAdded(jcf.modules[obj.name]);
				}
			}
		}
	},
	// add plugin to jcf.plugins
	addPlugin: function(obj) {
		if(obj && obj.name) {
			jcf.plugins[obj.name] = function() {
				this.init.apply(this, arguments);
			}
			for(var p in obj) {
				jcf.plugins[obj.name].prototype[p] = obj[p];
			}
		}
	},
	// miscellaneous init
	init: function(){
		this.eventPress = this.isTouchDevice ? 'touchstart' : 'mousedown';
		this.eventMove = this.isTouchDevice ? 'touchmove' : 'mousemove';
		this.eventRelease = this.isTouchDevice ? 'touchend' : 'mouseup';
		return this;
	}
}.init();

/*
 * Custom Form Control prototype
 */
jcf.setBaseModule({
	init: function(){
		if(this.options.replaces) {
			this.realElement = this.options.replaces;
			this.realElement.jcf = this;
			this.replaceObject();
		}
	},
	defaultOptions: {
		// default module options (will be merged with base options)
	},
	checkElement: function(el){
		return true; // additional check for correct form element
	},
	replaceObject: function(){
		this.createWrapper();
		this.attachEvents();
		this.fixStyles();
		this.setupWrapper();
	},
	createWrapper: function(){
		this.fakeElement = jcf.lib.createElement(this.options.wrapperTag);
		this.labelFor = jcf.lib.getLabelFor(this.realElement);
		jcf.lib.disableTextSelection(this.fakeElement);
		jcf.lib.addClass(this.realElement, jcf.baseOptions.hiddenClass);
	},
	attachEvents: function(){
		jcf.lib.event.add(this.realElement, 'focus', this.onFocusHandler, this);
		jcf.lib.event.add(this.realElement, 'blur', this.onBlurHandler, this);
		jcf.lib.event.add(this.fakeElement, 'click', this.onFakeClick, this);
		jcf.lib.event.add(this.fakeElement, jcf.eventPress, this.onFakePressed, this);
		jcf.lib.event.add(this.fakeElement, jcf.eventRelease, this.onFakeReleased, this);

		if(this.labelFor) {
			this.labelFor.jcf = this;
			jcf.lib.event.add(this.labelFor, 'click', this.onFakeClick, this);
			jcf.lib.event.add(this.labelFor, jcf.eventPress, this.onFakePressed, this);
			jcf.lib.event.add(this.labelFor, jcf.eventRelease, this.onFakeReleased, this);
		}
	},
	fixStyles: function() {
		// hide mobile webkit tap effect
		var tapStyle = 'rgba(255,255,255,0)';
		this.realElement.style.webkitTapHighlightColor = tapStyle;
		this.fakeElement.style.webkitTapHighlightColor = tapStyle;
		if(this.labelFor) {
			this.labelFor.style.webkitTapHighlightColor = tapStyle;
		}
	},
	setupWrapper: function(){
		// implement in subclass
	},
	refreshState: function(){
		// implement in subclass
	},
	destroy: function() {
		if(this.fakeElement && this.fakeElement.parentNode) {
			this.fakeElement.parentNode.removeChild(this.fakeElement);
		}
		jcf.lib.removeClass(this.realElement, jcf.baseOptions.hiddenClass);
		this.realElement.jcf = null;
	},
	onFocus: function(){
		// emulated focus event
		jcf.lib.addClass(this.fakeElement,this.options.focusClass);
	},
	onBlur: function(cb){
		// emulated blur event
		jcf.lib.removeClass(this.fakeElement,this.options.focusClass);
	},
	onFocusHandler: function() {
		// handle focus loses
		if(this.focused) return;
		this.focused = true;

		// handle touch devices also
		if(jcf.isTouchDevice) {
			if(jcf.focusedInstance && jcf.focusedInstance.realElement != this.realElement) {
				jcf.focusedInstance.onBlur();
				jcf.focusedInstance.realElement.blur();
			}
			jcf.focusedInstance = this;
		}
		this.onFocus.apply(this, arguments);
	},
	onBlurHandler: function() {
		// handle focus loses
		if(!this.pressedFlag) {
			this.focused = false;
			this.onBlur.apply(this, arguments);
		}
	},
	onFakeClick: function(){
		if(jcf.isTouchDevice) {
			this.onFocus();
		} else {
			this.realElement.focus();
		}
	},
	onFakePressed: function(e){
		this.pressedFlag = true;
	},
	onFakeReleased: function(){
		this.pressedFlag = false;
	},
	onCreateModule: function(){
		// implement in subclass
	},
	onModuleAdded: function(module) {
		// implement in subclass
	},
	onControlReady: function() {
		// implement in subclass
	}
});

/*
 * JCF Utility Library
 */
jcf.lib = {
	bind: function(func, scope){
		return function() {
			return func.apply(scope, arguments);
		}
	},
	browser: (function() {
		var ua = navigator.userAgent.toLowerCase(), res = {},
		match = /(webkit)[ \/]([\w.]+)/.exec(ua) || /(opera)(?:.*version)?[ \/]([\w.]+)/.exec(ua) ||
				/(msie) ([\w.]+)/.exec(ua) || ua.indexOf("compatible") < 0 && /(mozilla)(?:.*? rv:([\w.]+))?/.exec(ua) || [];
		res[match[1]] = true;
		res.version = match[2] || "0";
		res.safariMac = ua.indexOf('mac') != -1 && ua.indexOf('safari') != -1;
		return res;
	})(),
	getOffset: function (obj) {
		if (obj.getBoundingClientRect) {
			var scrollLeft = window.pageXOffset || document.documentElement.scrollLeft || document.body.scrollLeft;
			var scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
			var clientLeft = document.documentElement.clientLeft || document.body.clientLeft || 0;
			var clientTop = document.documentElement.clientTop || document.body.clientTop || 0;
			return {
				top:Math.round(obj.getBoundingClientRect().top + scrollTop - clientTop),
				left:Math.round(obj.getBoundingClientRect().left + scrollLeft - clientLeft)
			}
		} else {
			var posLeft = 0, posTop = 0;
			while (obj.offsetParent) {posLeft += obj.offsetLeft; posTop += obj.offsetTop; obj = obj.offsetParent;}
			return {top:posTop,left:posLeft};
		}
	},
	getScrollTop: function() {
		return window.pageYOffset || document.documentElement.scrollTop;
	},
	getScrollLeft: function() {
		return window.pageXOffset || document.documentElement.scrollLeft;
	},
	getWindowWidth: function(){
		return document.compatMode=='CSS1Compat' ? document.documentElement.clientWidth : document.body.clientWidth;
	},
	getWindowHeight: function(){
		return document.compatMode=='CSS1Compat' ? document.documentElement.clientHeight : document.body.clientHeight;
	},
	getStyle: function(el, prop) {
		if (document.defaultView && document.defaultView.getComputedStyle) {
			return document.defaultView.getComputedStyle(el, null)[prop];
		} else if (el.currentStyle) {
			return el.currentStyle[prop];
		} else {
			return el.style[prop];
		}
	},
	getParent: function(obj, selector) {
		while(obj.parentNode && obj.parentNode != document.body) {
			if(obj.parentNode.tagName.toLowerCase() == selector.toLowerCase()) {
				return obj.parentNode;
			}
			obj = obj.parentNode;
		}
		return false;
	},
	isParent: function(child, parent) {
		while(child.parentNode) {
			if(child.parentNode === parent) {
				return true;
			}
			child = child.parentNode;
		}
		return false;
	},
	getLabelFor: function(object) {
		if(jcf.lib.getParent(object,'label')) {
			return object.parentNode;
		} else if(object.id) {
			return jcf.lib.queryBySelector('label[for=' + object.id + ']')[0];
		}
	},
	disableTextSelection: function(el){
		el.setAttribute('unselectable', 'on');
		el.style.MozUserSelect = 'none';
		el.style.WebkitUserSelect = 'none';
		el.style.UserSelect = 'none';
		el.onselectstart = function() {return false};
	},
	enableTextSelection: function(el) {
		el.removeAttribute('unselectable');
		el.style.MozUserSelect = '';
		el.style.WebkitUserSelect = '';
		el.style.UserSelect = '';
		el.onselectstart = null;
	},
	queryBySelector: function(selector, scope){
		return this.getElementsBySelector(selector, scope);
	},
	prevSibling: function(node) {
		while(node = node.previousSibling) if(node.nodeType == 1) break;
		return node;
	},
	nextSibling: function(node) {
		while(node = node.nextSibling) if(node.nodeType == 1) break;
		return node;
	},
	fireEvent: function(element,event) {
		if (document.createEventObject){
			var evt = document.createEventObject();
			return element.fireEvent('on'+event,evt)
		}
		else{
			var evt = document.createEvent('HTMLEvents');
			evt.initEvent(event, true, true );
			return !element.dispatchEvent(evt);
		}
	},
	isParent: function(p, c) {
		while(c.parentNode) {
			if(p == c) {
				return true;
			}
			c = c.parentNode;
		}
		return false;
	},
	inherit: function(Child, Parent) {
		var F = function() { }
		F.prototype = Parent.prototype
		Child.prototype = new F()
		Child.prototype.constructor = Child
		Child.superclass = Parent.prototype
	},
	extend: function(obj) {
		for(var i = 1; i < arguments.length; i++) {
			for(var p in arguments[i]) {
				if(arguments[i].hasOwnProperty(p)) {
					obj[p] = arguments[i][p];
				}
			}
		}
		return obj;
	},
	hasClass: function (obj,cname) {
		return (obj.className ? obj.className.match(new RegExp('(\\s|^)'+cname+'(\\s|$)')) : false);
	},
	addClass: function (obj,cname) {
		if (!this.hasClass(obj,cname)) obj.className += " "+cname;
	},
	removeClass: function (obj,cname) {
		if (this.hasClass(obj,cname)) obj.className=obj.className.replace(new RegExp('(\\s|^)'+cname+'(\\s|$)'),' ');
	},
	toggleClass: function(obj, cname, condition) {
		if(condition) this.addClass(obj, cname); else this.removeClass(obj, cname);
	},
	createElement: function(tagName, options) {
		var el = document.createElement(tagName);
		for(var p in options) {
			if(options.hasOwnProperty(p)) {
				switch (p) {
					case 'class': el.className = options[p]; break;
					case 'html': el.innerHTML = options[p]; break;
					case 'style': this.setStyles(el, options[p]); break;
					default: el.setAttribute(p, options[p]);
				}
			}
		}
		return el;
	},
	setStyles: function(el, styles) {
		for(var p in styles) {
			if(styles.hasOwnProperty(p)) {
				switch (p) {
					case 'float': el.style.cssFloat = styles[p]; break;
					case 'opacity': el.style.filter = 'progid:DXImageTransform.Microsoft.Alpha(opacity='+styles[p]*100+')'; el.style.opacity = styles[p]; break;
					default: el.style[p] = (typeof styles[p] === 'undefined' ? 0 : styles[p]) + (typeof styles[p] === 'number' ? 'px' : '');
				}
			}
		}
		return el;
	},
	getInnerWidth: function(el) {
		return el.offsetWidth - (parseInt(this.getStyle(el,'paddingLeft')) || 0) - (parseInt(this.getStyle(el,'paddingRight')) || 0);
	},
	getInnerHeight: function(el) {
		return el.offsetHeight - (parseInt(this.getStyle(el,'paddingTop')) || 0) - (parseInt(this.getStyle(el,'paddingBottom')) || 0);
	},
	getAllClasses: function(cname, prefix, skip) {
		if(!skip) skip = '';
		if(!prefix) prefix = '';
		return cname ? cname.replace(new RegExp('(\\s|^)'+skip+'(\\s|$)'),' ').replace(/[\s]*([\S]+)+[\s]*/gi,prefix+"$1 ") : '';
	},
	getElementsBySelector: function(selector, scope) {
		if(typeof document.querySelectorAll === 'function') {
			return (scope || document).querySelectorAll(selector);
		}
		var selectors = selector.split(',');
		var resultList = [];
		for(var s = 0; s < selectors.length; s++) {
			var currentContext = [scope || document];
			var tokens = selectors[s].replace(/^\s+/,'').replace(/\s+$/,'').split(' ');
			for (var i = 0; i < tokens.length; i++) {
				token = tokens[i].replace(/^\s+/,'').replace(/\s+$/,'');
				if (token.indexOf('#') > -1) {
					var bits = token.split('#'), tagName = bits[0], id = bits[1];
					var element = document.getElementById(id);
					if (tagName && element.nodeName.toLowerCase() != tagName) {
						return [];
					}
					currentContext = [element];
					continue;
				}
				if (token.indexOf('.') > -1) {
					var bits = token.split('.'), tagName = bits[0] || '*', className = bits[1], found = [], foundCount = 0;
					for (var h = 0; h < currentContext.length; h++) {
						var elements;
						if (tagName == '*') {
							elements = currentContext[h].getElementsByTagName('*');
						} else {
							elements = currentContext[h].getElementsByTagName(tagName);
						}
						for (var j = 0; j < elements.length; j++) {
							found[foundCount++] = elements[j];
						}
					}
					currentContext = [];
					var currentContextIndex = 0;
					for (var k = 0; k < found.length; k++) {
						if (found[k].className && found[k].className.match(new RegExp('(\\s|^)'+className+'(\\s|$)'))) {
							currentContext[currentContextIndex++] = found[k];
						}
					}
					continue;
				}
				if (token.match(/^(\w*)\[(\w+)([=~\|\^\$\*]?)=?"?([^\]"]*)"?\]$/)) {
					var tagName = RegExp.$1 || '*', attrName = RegExp.$2, attrOperator = RegExp.$3, attrValue = RegExp.$4;
					if(attrName.toLowerCase() == 'for' && this.browser.msie && this.browser.version < 8) {
						attrName = 'htmlFor';
					}
					var found = [], foundCount = 0;
					for (var h = 0; h < currentContext.length; h++) {
						var elements;
						if (tagName == '*') {
							elements = currentContext[h].getElementsByTagName('*');
						} else {
							elements = currentContext[h].getElementsByTagName(tagName);
						}
						for (var j = 0; j < elements.length; j++) {
							found[foundCount++] = elements[j];
						}
					}
					currentContext = [];
					var currentContextIndex = 0, checkFunction;
					switch (attrOperator) {
						case '=': checkFunction = function(e) { return (e.getAttribute(attrName) == attrValue) }; break;
						case '~': checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('(\\s|^)'+attrValue+'(\\s|$)'))) }; break;
						case '|': checkFunction = function(e) { return (e.getAttribute(attrName).match(new RegExp('^'+attrValue+'-?'))) }; break;
						case '^': checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) == 0) }; break;
						case '$': checkFunction = function(e) { return (e.getAttribute(attrName).lastIndexOf(attrValue) == e.getAttribute(attrName).length - attrValue.length) }; break;
						case '*': checkFunction = function(e) { return (e.getAttribute(attrName).indexOf(attrValue) > -1) }; break;
						default : checkFunction = function(e) { return e.getAttribute(attrName) };
					}
					currentContext = [];
					var currentContextIndex = 0;
					for (var k = 0; k < found.length; k++) {
						if (checkFunction(found[k])) {
							currentContext[currentContextIndex++] = found[k];
						}
					}
					continue;
				}
				tagName = token;
				var found = [], foundCount = 0;
				for (var h = 0; h < currentContext.length; h++) {
					var elements = currentContext[h].getElementsByTagName(tagName);
					for (var j = 0; j < elements.length; j++) {
						found[foundCount++] = elements[j];
					}
				}
				currentContext = found;
			}
			resultList = [].concat(resultList,currentContext);
		}
		return resultList;
	},
	scrollSize: (function(){
		var content, hold, sizeBefore, sizeAfter;
		function buildSizer(){
			if(hold) removeSizer();
			content = document.createElement('div');
			hold = document.createElement('div');
			hold.style.cssText = 'position:absolute;overflow:hidden;width:100px;height:100px';
			hold.appendChild(content);
			document.body.appendChild(hold);
		}
		function removeSizer(){
			document.body.removeChild(hold);
			hold = null;
		}
		function calcSize(vertical) {
			buildSizer();
			content.style.cssText = 'height:'+(vertical ? '100%' : '200px');
			sizeBefore = (vertical ? content.offsetHeight : content.offsetWidth);
			hold.style.overflow = 'scroll'; content.innerHTML = 1;
			sizeAfter = (vertical ? content.offsetHeight : content.offsetWidth);
			if(vertical && hold.clientHeight) sizeAfter = hold.clientHeight;
			removeSizer();
			return sizeBefore - sizeAfter;
		}
		return {
			getWidth:function(){
				return calcSize(false);
			},
			getHeight:function(){
				return calcSize(true)
			}
		}
	}()),
	domReady: function (handler){
		var called = false
		function ready() {
			if (called) return;
			called = true;
			handler();
		}
		if (document.addEventListener) {
			document.addEventListener("DOMContentLoaded", ready, false);
		} else if (document.attachEvent) {
			if (document.documentElement.doScroll && window == window.top) {
				function tryScroll(){
					if (called) return
					if (!document.body) return
					try {
						document.documentElement.doScroll("left")
						ready()
					} catch(e) {
						setTimeout(tryScroll, 0)
					}
				}
				tryScroll()
			}
			document.attachEvent("onreadystatechange", function(){
				if (document.readyState === "complete") {
					ready()
				}
			})
		}
		if (window.addEventListener) window.addEventListener('load', ready, false)
		else if (window.attachEvent) window.attachEvent('onload', ready)
	},
	event: (function(){
		var guid = 0;
		function fixEvent(e) {
			e = e || window.event;
			if (e.isFixed) {
				return e;
			}
			e.isFixed = true;
			e.preventDefault = e.preventDefault || function(){this.returnValue = false}
			e.stopPropagation = e.stopPropagaton || function(){this.cancelBubble = true}
			if (!e.target) {
				e.target = e.srcElement
			}
			if (!e.relatedTarget && e.fromElement) {
				e.relatedTarget = e.fromElement == e.target ? e.toElement : e.fromElement;
			}
			if (e.pageX == null && e.clientX != null) {
				var html = document.documentElement, body = document.body;
				e.pageX = e.clientX + (html && html.scrollLeft || body && body.scrollLeft || 0) - (html.clientLeft || 0);
				e.pageY = e.clientY + (html && html.scrollTop || body && body.scrollTop || 0) - (html.clientTop || 0);
			}
			if (!e.which && e.button) {
				e.which = e.button & 1 ? 1 : (e.button & 2 ? 3 : (e.button & 4 ? 2 : 0));
			}
			if(e.type === "DOMMouseScroll" || e.type === 'mousewheel') {
				e.mWheelDelta = 0;
				if (e.wheelDelta) {
					e.mWheelDelta = e.wheelDelta/120;
				} else if (e.detail) {
					e.mWheelDelta = -e.detail/3;
				}
			}
			return e;
		}
		function commonHandle(event, customScope) {
			event = fixEvent(event);
			var handlers = this.events[event.type];
			for (var g in handlers) {
				var handler = handlers[g];
				var ret = handler.call(customScope || this, event);
				if (ret === false) {
					event.preventDefault()
					event.stopPropagation()
				}
			}
		}
		var publicAPI = {
			add: function(elem, type, handler, forcedScope) {
				if (elem.setInterval && (elem != window && !elem.frameElement)) {
					elem = window;
				}
				if (!handler.guid) {
					handler.guid = ++guid;
				}
				if (!elem.events) {
					elem.events = {};
					elem.handle = function(event) {
						return commonHandle.call(elem, event);
					}
				}
				if (!elem.events[type]) {
					elem.events[type] = {};
					if (elem.addEventListener) elem.addEventListener(type, elem.handle, false);
					else if (elem.attachEvent) elem.attachEvent("on" + type, elem.handle);
					if(type === 'mousewheel') {
						publicAPI.add(elem, 'DOMMouseScroll', handler, forcedScope);
					}
				}
				var fakeHandler = jcf.lib.bind(handler, forcedScope);
				fakeHandler.guid = handler.guid;
				elem.events[type][handler.guid] = forcedScope ? fakeHandler : handler;
			},
			remove: function(elem, type, handler) {
				var handlers = elem.events && elem.events[type];
				if (!handlers) return;
				delete handlers[handler.guid];
				for(var any in handlers) return;
				if (elem.removeEventListener) elem.removeEventListener(type, elem.handle, false);
				else if (elem.detachEvent) elem.detachEvent("on" + type, elem.handle);
				delete elem.events[type];
				for (var any in elem.events) return;
				try {
					delete elem.handle;
					delete elem.events;
				} catch(e) {
					if(elem.removeAttribute) {
						elem.removeAttribute("handle");
						elem.removeAttribute("events");
					}
				}
				if(type === 'mousewheel') {
					publicAPI.remove(elem, 'DOMMouseScroll', handler);
				}
			}
		}
		return publicAPI;
	}())
};

// custom select module
jcf.addModule({
	name:'select',
	selector:'select',
	defaultOptions: {
		handleDropPosition:false,
		wrapperClass:'select-area',
		focusClass:'select-focus',
		dropActiveClass:'select-active',
		selectedClass:'item-selected',
		disabledClass:'select-disabled',
		valueSelector:'span.center',
		optGroupClass:'optgroup',
		openerSelector:'a.select-opener',
		selectStructure:'<span class="left"></span><span class="center"></span><a class="select-opener"></a>',
		selectPrefixClass:'select-',
		dropMaxHeight: 200,
		dropFlippedClass: 'select-options-flipped',
		dropHiddenClass:'options-hidden',
		dropScrollableClass:'options-overflow',
		dropClass:'select-options',
		dropClassPrefix:'drop-',
		dropStructure:'<div class="drop-holder"><div class="drop-list"></div></div>',
		dropSelector:'div.drop-list'
	},
	checkElement: function(el){
		return (!el.size && !el.multiple);
	},
	setupWrapper: function(){
		jcf.lib.addClass(this.fakeElement, this.options.wrapperClass);
		this.realElement.parentNode.insertBefore(this.fakeElement, this.realElement);
		this.fakeElement.innerHTML = this.options.selectStructure;
		this.fakeElement.style.width = this.realElement.offsetWidth + 'px';
		jcf.lib.addClass(this.fakeElement, jcf.lib.getAllClasses(this.realElement.className, this.options.selectPrefixClass, jcf.baseOptions.hiddenClass));

		// create select body
		this.opener = jcf.lib.queryBySelector(this.options.openerSelector, this.fakeElement)[0];
		this.valueText = jcf.lib.queryBySelector(this.options.valueSelector, this.fakeElement)[0];
		this.opener.jcf = this;

		this.createDropdown();
		this.refreshState();
		this.addEvents();
		this.onControlReady(this);
		this.hideDropdown(true);
	},
	addEvents: function(){
		jcf.lib.event.add(this.fakeElement, 'click', this.toggleDropdown, this);
		jcf.lib.event.add(this.realElement, 'change', this.onChange, this);
	},
	onFakeClick: function() {
		// do nothing (drop toggles by toggleDropdown method)
	},
	onFocus: function(){
		// Mac Safari Fix
		if(jcf.lib.browser.safariMac) {
			this.realElement.setAttribute('size','2');
		}
		jcf.modules[this.name].superclass.onFocus.apply(this, arguments);
		jcf.lib.event.add(this.realElement, 'keydown', this.onKeyDown, this);
		if(jcf.activeControl && jcf.activeControl != this) {
			jcf.activeControl.hideDropdown();
			jcf.activeControl = this;
		}
	},
	onBlur: function(){
		// Mac Safari Fix
		if(jcf.lib.browser.safariMac) {
			this.realElement.removeAttribute('size');
		}
		if(!this.isActiveDrop() || !this.isOverDrop()) {
			jcf.modules[this.name].superclass.onBlur.apply(this);
			if(jcf.activeControl === this) jcf.activeControl = null;
			if(!jcf.isTouchDevice) {
				this.hideDropdown();
			}
		}
		jcf.lib.event.remove(this.realElement, 'keydown', this.onKeyDown);
	},
	onChange: function() {
		this.refreshState();
	},
	onKeyDown: function(e){
		jcf.tmpFlag = true;
		setTimeout(function(){jcf.tmpFlag = false},100);
		var context = this;
		context.keyboardFix = true;
		setTimeout(function(){
			context.refreshState();
		},10);
		if(e.keyCode == 13) {
			context.toggleDropdown.apply(context);
			return false;
		}
	},
	onResizeWindow: function(e){
		if(this.isActiveDrop()) {
			this.hideDropdown();
		}
	},
	onScrollWindow: function(e){
		if(this.isActiveDrop()) {
			this.positionDropdown();
		}
	},
	onOptionClick: function(e){
		var opener = e.target && e.target.tagName && e.target.tagName.toLowerCase() == 'li' ? e.target : jcf.lib.getParent(e.target, 'li');
		if(opener) {
			this.realElement.selectedIndex = parseInt(opener.getAttribute('rel'));
			if(jcf.isTouchDevice) {
				this.onFocus();
			} else {
				this.realElement.focus();
			}
			this.refreshState();
			this.hideDropdown();
			jcf.lib.fireEvent(this.realElement, 'change');
		}
		return false;
	},
	onClickOutside: function(e){
		if(jcf.tmpFlag) {
			jcf.tmpFlag = false;
			return;
		}
		if(!jcf.lib.isParent(this.fakeElement, e.target) && !jcf.lib.isParent(this.selectDrop, e.target)) {
			this.hideDropdown();
		}
	},
	onDropHover: function(e){
		if(!this.keyboardFix) {
			this.hoverFlag = true;
			var opener = e.target && e.target.tagName && e.target.tagName.toLowerCase() == 'li' ? e.target : jcf.lib.getParent(e.target, 'li');
			if(opener) {
				this.realElement.selectedIndex = parseInt(opener.getAttribute('rel'));
				this.refreshSelectedClass(parseInt(opener.getAttribute('rel')));
			}
		} else {
			this.keyboardFix = false;
		}
	},
	onDropLeave: function(){
		this.hoverFlag = false;
	},
	isActiveDrop: function(){
		return !jcf.lib.hasClass(this.selectDrop, this.options.dropHiddenClass);
	},
	isOverDrop: function(){
		return this.hoverFlag;
	},
	createDropdown: function(){
		// remove old dropdown if exists
		if(this.selectDrop) {
			this.selectDrop.parentNode.removeChild(this.selectDrop);
		}

		// create dropdown holder
		this.selectDrop = document.createElement('div');
		this.selectDrop.className = this.options.dropClass;
		this.selectDrop.innerHTML = this.options.dropStructure;
		this.selectList = jcf.lib.queryBySelector(this.options.dropSelector,this.selectDrop)[0];
		jcf.lib.addClass(this.selectDrop, this.options.dropHiddenClass);
		document.body.appendChild(this.selectDrop);
		this.selectDrop.jcf = this;
		jcf.lib.event.add(this.selectDrop, 'click', this.onOptionClick, this);
		jcf.lib.event.add(this.selectDrop, 'mouseover', this.onDropHover, this);
		jcf.lib.event.add(this.selectDrop, 'mouseout', this.onDropLeave, this);
		this.buildDropdown();
	},
	buildDropdown: function() {
		// build select options / optgroups
		this.buildDropdownOptions();

		// position and resize dropdown
		this.positionDropdown();

		// cut dropdown if height exceedes
		this.buildDropdownScroll();
	},
	buildDropdownOptions: function() {
		this.resStructure = '';
		this.optNum = 0;
		for(var i = 0; i < this.realElement.children.length; i++) {
			this.resStructure += this.buildElement(this.realElement.children[i]) +'\n';
		}
		this.selectList.innerHTML = this.resStructure;
	},
	buildDropdownScroll: function() {
		if(this.options.dropMaxHeight) {
			if(this.selectDrop.offsetHeight > this.options.dropMaxHeight) {
				this.selectList.style.height = this.options.dropMaxHeight+'px';
				this.selectList.style.overflow = 'auto';
				this.selectList.style.overflowX = 'hidden';
				jcf.lib.addClass(this.selectDrop, this.options.dropScrollableClass);
			}
		}
		jcf.lib.addClass(this.selectDrop, jcf.lib.getAllClasses(this.realElement.className, this.options.dropClassPrefix, jcf.baseOptions.hiddenClass));
	},
	buildElement: function(obj){
		// build option
		var res = '';
		if(obj.tagName.toLowerCase() == 'option') {
			if(!jcf.lib.prevSibling(obj) || jcf.lib.prevSibling(obj).tagName.toLowerCase() != 'option') {
				res += '<ul>';
			}
			res += '<li rel="'+(this.optNum++)+'" class="'+(obj.className? obj.className : '')+' jcfcalc"><a href="#">'+(obj.title? '<img src="'+obj.title+'" alt="" />' : '')+'<span>' + obj.innerHTML + '</span></a></li>';
			if(!jcf.lib.nextSibling(obj) || jcf.lib.nextSibling(obj).tagName.toLowerCase() != 'option') {
				res += '</ul>';
			}
			return res;
		}
		// build option group with options
		else if(obj.tagName.toLowerCase() == 'optgroup' && obj.label) {
			res += '<div class="'+this.options.optGroupClass+'">';
			res += '<strong class="jcfcalc"><em>'+(obj.label)+'</em></strong>';
			for(var i = 0; i < obj.children.length; i++) {
				res += this.buildElement(obj.children[i]);
			}
			res += '</div>';
			return res;
		}
	},
	positionDropdown: function(){
		var ofs = jcf.lib.getOffset(this.fakeElement), selectAreaHeight = this.fakeElement.offsetHeight, selectDropHeight = this.selectDrop.offsetHeight;
		if(this.options.handleDropPosition && jcf.lib.getScrollTop() + jcf.lib.getWindowHeight() < ofs.top + selectAreaHeight + selectDropHeight) {
			this.selectDrop.style.top = (ofs.top - selectDropHeight)+'px';
			jcf.lib.addClass(this.selectDrop, this.options.dropFlippedClass);
		} else {
			this.selectDrop.style.top = (ofs.top + selectAreaHeight)+'px';
			jcf.lib.removeClass(this.selectDrop, this.options.dropFlippedClass);
		}
		this.selectDrop.style.left = ofs.left+'px';
		this.selectDrop.style.width = this.fakeElement.offsetWidth+'px';
	},
	showDropdown: function(){
		document.body.appendChild(this.selectDrop);
		jcf.lib.removeClass(this.selectDrop, this.options.dropHiddenClass);
		jcf.lib.addClass(this.fakeElement,this.options.dropActiveClass);
		this.positionDropdown();

		// show current dropdown
		jcf.lib.event.add(window, 'resize', this.onResizeWindow, this);
		jcf.lib.event.add(window, 'scroll', this.onScrollWindow, this);
		jcf.lib.event.add(document, jcf.eventPress, this.onClickOutside, this);
		this.positionDropdown();
	},
	hideDropdown: function(partial){
		if(this.selectDrop.parentNode) {
			if(this.selectDrop.offsetWidth) {
				this.selectDrop.parentNode.removeChild(this.selectDrop);
			}
			if(partial) {
				return;
			}
		}
		if(typeof this.origSelectedIndex === 'number') {
			this.realElement.selectedIndex = this.origSelectedIndex;
		}
		jcf.lib.removeClass(this.fakeElement,this.options.dropActiveClass);
		jcf.lib.addClass(this.selectDrop, this.options.dropHiddenClass);
		jcf.lib.event.remove(window, 'resize', this.onResizeWindow);
		jcf.lib.event.remove(window, 'scroll', this.onScrollWindow);
		jcf.lib.event.remove(document.documentElement, jcf.eventPress, this.onClickOutside);
		if(jcf.isTouchDevice) {
			this.onBlur();
		}
	},
	toggleDropdown: function(){
		if(jcf.isTouchDevice) {
			this.onFocus();
		} else {
			this.realElement.focus();
		}
		this.dropOpened = true;
		if(!this.realElement.disabled) {
			if(this.isActiveDrop()) {
				this.hideDropdown();
			} else {
				this.showDropdown();
			}
		}
		this.refreshState();
	},
	scrollToItem: function(){
		if(this.isActiveDrop()) {
			var dropHeight = this.selectList.offsetHeight;
			var offsetTop = this.calcOptionOffset(this.getFakeActiveOption());
			var sTop = this.selectList.scrollTop;
			var oHeight = this.getFakeActiveOption().offsetHeight;
			//offsetTop+=sTop;

			if(offsetTop >= sTop + dropHeight) {
				this.selectList.scrollTop = offsetTop - dropHeight + oHeight;
			} else if(offsetTop < sTop) {
				this.selectList.scrollTop = offsetTop;
			}
		}
	},
	getFakeActiveOption: function(c) {
		return jcf.lib.queryBySelector('li[rel="'+(typeof c === 'number' ? c : this.realElement.selectedIndex) +'"]',this.selectList)[0];
	},
	calcOptionOffset: function(fake) {
		var h = 0;
		var els = jcf.lib.queryBySelector('.jcfcalc',this.selectList);
		for(var i = 0; i < els.length; i++) {
			if(els[i] == fake) break;
			h+=els[i].offsetHeight;
		}
		return h;
	},
	childrenHasItem: function(hold,item) {
		var items = hold.getElementsByTagName('*');
		for(i = 0; i < items.length; i++) {
			if(items[i] == item) return true;
		}
		return false;
	},
	removeSelectedClass: function(){
		var children = jcf.lib.queryBySelector('li',this.selectList);
		for(var i = children.length - 1; i >= 0; i--) {
			jcf.lib.removeClass(children[i], this.options.selectedClass);
		}
	},
	setSelectedClass: function(c){
		jcf.lib.addClass(this.getFakeActiveOption(c), this.options.selectedClass);
	},
	refreshSelectedClass: function(c){
		this.removeSelectedClass(c);
		this.setSelectedClass(c);
		if(this.realElement.disabled) {
			jcf.lib.addClass(this.fakeElement, this.options.disabledClass);
		} else {
			jcf.lib.removeClass(this.fakeElement, this.options.disabledClass);
		}
	},
	refreshSelectedText: function() {
		if(!this.dropOpened && this.realElement.title) {
			this.valueText.innerHTML = this.realElement.title;
		} else {
			if(this.realElement.options[this.realElement.selectedIndex].title) {
				this.valueText.innerHTML = '<img src="'+this.realElement.options[this.realElement.selectedIndex].title+'" alt="" />' + this.realElement.options[this.realElement.selectedIndex].innerHTML;
			} else {
				this.valueText.innerHTML = this.realElement.options[this.realElement.selectedIndex].innerHTML;
			}
		}
	},
	refreshState: function(){
		this.origSelectedIndex = this.realElement.selectedIndex;
		this.refreshSelectedClass();
		this.refreshSelectedText();
		this.positionDropdown();
		if(this.selectDrop.offsetWidth) {
			this.scrollToItem();
		}
	}
});

// custom scrollbars module
jcf.addModule({
	name:'customscroll',
	selector:'div.scrollable-area',
	defaultOptions: {
		alwaysPreventWheel: false,
		enableMouseWheel: true,
		captureFocus: false,
		handleNested: true,
		alwaysKeepScrollbars: false,
		scrollbarOptions: {},
		focusClass:'scrollable-focus',
		wrapperTag: 'div',
		noHorizontalBarClass:'noscroll-horizontal',
		noVerticalBarClass:'noscroll-vertical',
		innerWrapperClass:'scrollable-inner-wrapper',
		outerWrapperClass:'scrollable-area-wrapper',
		horizontalClass: 'hscrollable',
		verticalClass: 'vscrollable',
		bothClass: 'anyscrollable'
	},
	replaceObject: function(){
		this.initStructure();
		this.refreshState();
		this.addEvents();
	},
	initStructure: function(){
		// set scroll type
		this.realElement.jcf = this;
		if(jcf.lib.hasClass(this.realElement, this.options.bothClass) ||
		jcf.lib.hasClass(this.realElement, this.options.horizontalClass) && jcf.lib.hasClass(this.realElement, this.options.verticalClass)) {
			this.scrollType = 'both';
		} else if(jcf.lib.hasClass(this.realElement, this.options.horizontalClass)) {
			this.scrollType = 'horizontal';
		} else {
			this.scrollType = 'vertical';
		}

		// init dimensions and build structure
		this.realElement.style.position = 'relative';
		this.realElement.style.overflow = 'hidden';

		// build content wrapper and scrollbar(s)
		this.buildWrapper();
		this.buildScrollbars();
	},
	buildWrapper: function() {
		this.outerWrapper = document.createElement(this.options.wrapperTag);
		this.outerWrapper.className = this.options.outerWrapperClass;
		this.realElement.parentNode.insertBefore(this.outerWrapper, this.realElement);
		this.outerWrapper.appendChild(this.realElement);
	},
	buildScrollbars: function() {
		if(this.scrollType === 'horizontal' || this.scrollType === 'both') {
			this.hScrollBar = new jcf.plugins.scrollbar(jcf.lib.extend(this.options.scrollbarOptions,{
				vertical: false,
				spawnClass: this,
				holder: this.outerWrapper,
				range: this.realElement.scrollWidth - this.realElement.offsetWidth,
				size: this.realElement.offsetWidth,
				onScroll: jcf.lib.bind(function(v) {
					this.realElement.scrollLeft = v;
				},this)
			}));
		}
		if(this.scrollType === 'vertical' || this.scrollType === 'both') {
			this.vScrollBar = new jcf.plugins.scrollbar(jcf.lib.extend(this.options.scrollbarOptions,{
				vertical: true,
				spawnClass: this,
				holder: this.outerWrapper,
				range: this.realElement.scrollHeight - this.realElement.offsetHeight,
				size: this.realElement.offsetHeight,
				onScroll: jcf.lib.bind(function(v) {
					this.realElement.scrollTop = v;
				},this)
			}));
		}
		this.outerWrapper.style.width = this.realElement.offsetWidth + 'px';
		this.outerWrapper.style.height = this.realElement.offsetHeight + 'px';
		this.resizeScrollContent();
	},
	resizeScrollContent: function() {
		var diffWidth = this.realElement.offsetWidth - jcf.lib.getInnerWidth(this.realElement);
		var diffHeight = this.realElement.offsetHeight - jcf.lib.getInnerHeight(this.realElement);
		this.realElement.style.width = Math.max(0, this.outerWrapper.offsetWidth - diffWidth - (this.vScrollBar ? this.vScrollBar.getScrollBarSize() : 0)) + 'px';
		this.realElement.style.height = Math.max(0, this.outerWrapper.offsetHeight - diffHeight - (this.hScrollBar ? this.hScrollBar.getScrollBarSize() : 0)) + 'px';
	},
	addEvents: function() {
		// enable mouse wheel handling
		if(!jcf.isTouchDevice && this.options.enableMouseWheel) {
			jcf.lib.event.add(this.outerWrapper, 'mousewheel', this.onMouseWheel, this);
		}
		// add touch scroll on block body
		if(jcf.isTouchDevice) {
			jcf.lib.event.add(this.realElement, jcf.eventPress, this.onScrollablePress, this);
		}

		// handle nested scrollbars
		if(this.options.handleNested) {
			var el = this.realElement, name = this.name;
			while(el.parentNode) {
				if(el.parentNode.jcf && el.parentNode.jcf.name == name) {
					el.parentNode.jcf.refreshState();
				}
				el = el.parentNode;
			}
		}
	},
	onMouseWheel: function(e) {
		if(this.scrollType === 'vertical' || this.scrollType === 'both') {
			return this.vScrollBar.doScrollWheelStep(e.mWheelDelta) === false ? false : !this.options.alwaysPreventWheel;
		} else {
			return this.hScrollBar.doScrollWheelStep(e.mWheelDelta) === false ? false : !this.options.alwaysPreventWheel;
		}
	},
	onScrollablePress: function(e) {
		this.scrollableOffset = jcf.lib.getOffset(this.realElement);
		if(this.hScrollBar) {
			this.scrollableTouchX = (jcf.isTouchDevice ? e.changedTouches[0] : e).pageX;
			this.origValueX = this.hScrollBar.getScrollValue();
		}
		if(this.vScrollBar) {
			this.scrollableTouchY = (jcf.isTouchDevice ? e.changedTouches[0] : e).pageY;
			this.origValueY = this.vScrollBar.getScrollValue();
		}
		jcf.lib.event.add(this.realElement, jcf.eventMove, this.onScrollableMove, this);
		jcf.lib.event.add(this.realElement, jcf.eventRelease, this.onScrollableRelease, this);
	},
	onScrollableMove: function(e) {
		if(this.vScrollBar) {
			var difY = (jcf.isTouchDevice ? e.changedTouches[0] : e).pageY - this.scrollableTouchY;
			this.vScrollBar.scrollTo(this.origValueY-difY);
		}
		if(this.hScrollBar) {
			var difX = (jcf.isTouchDevice ? e.changedTouches[0] : e).pageX - this.scrollableTouchX;
			this.hScrollBar.scrollTo(this.origValueX-difX);
		}
		e.preventDefault();
	},
	onScrollableRelease: function() {
		jcf.lib.event.remove(this.realElement, jcf.eventMove, this.onScrollableMove);
		jcf.lib.event.remove(this.realElement, jcf.eventRelease, this.onScrollableRelease);
	},
	refreshState: function() {
		if(this.options.alwaysKeepScrollbars) {
			if(this.hScrollBar) this.hScrollBar.scrollBar.style.display = 'block';
			if(this.vScrollBar) this.vScrollBar.scrollBar.style.display = 'block';
		} else {
			if(this.hScrollBar) {
				if(this.getScrollRange(false)) {
					this.hScrollBar.scrollBar.style.display = 'block';
					this.resizeScrollContent();
					this.hScrollBar.setRange(this.getScrollRange(false));
				} else {
					this.hScrollBar.scrollBar.style.display = 'none';
					this.realElement.style.width = this.outerWrapper.style.width;
				}
				jcf.lib.toggleClass(this.outerWrapper, this.options.noHorizontalBarClass, this.hScrollBar.options.range === 0);
			}
			if(this.vScrollBar) {
				if(this.getScrollRange(true)) {
					this.vScrollBar.scrollBar.style.display = 'block';
					this.resizeScrollContent();
					this.vScrollBar.setRange(this.getScrollRange(true));
				} else {
					this.vScrollBar.scrollBar.style.display = 'none';
					this.realElement.style.width = this.outerWrapper.style.width;
				}
				jcf.lib.toggleClass(this.outerWrapper, this.options.noVerticalBarClass, this.vScrollBar.options.range === 0);
			}
		}
		if(this.vScrollBar) {
			this.vScrollBar.setRange(this.realElement.scrollHeight - this.realElement.offsetHeight);
			this.vScrollBar.setSize(this.realElement.offsetHeight);
			this.vScrollBar.scrollTo(this.realElement.scrollTop);
		}
		if(this.hScrollBar) {
			this.hScrollBar.setRange(this.realElement.scrollWidth - this.realElement.offsetWidth);
			this.hScrollBar.setSize(this.realElement.offsetWidth);
			this.hScrollBar.scrollTo(this.realElement.scrollLeft);
		}
	},
	getScrollRange: function(isVertical) {
		if(isVertical) {
			return this.realElement.scrollHeight - this.realElement.offsetHeight;
		} else {
			return this.realElement.scrollWidth - this.realElement.offsetWidth;
		}
	},
	getCurrentRange: function(scrollInstance) {
		return this.getScrollRange(scrollInstance.isVertical);
	},
	onCreateModule: function(){
		if(jcf.modules.select) {
			this.extendSelect();
		}
		if(jcf.modules.selectmultiple) {
			this.extendSelectMultiple();
		}
		if(jcf.modules.textarea) {
			this.extendTextarea();
		}
	},
	onModuleAdded: function(module){
		if(module.prototype.name == 'select') {
			this.extendSelect();
		}
		if(module.prototype.name == 'selectmultiple') {
			this.extendSelectMultiple();
		}
		if(module.prototype.name == 'textarea') {
			this.extendTextarea();
		}
	},
	extendSelect: function() {
		// add scrollable if needed on control ready
		jcf.modules.select.prototype.onControlReady = function(obj){
			if(obj.selectList.scrollHeight > obj.selectList.offsetHeight) {
				obj.jcfScrollable = new jcf.modules.customscroll({
					alwaysPreventWheel: true,
					replaces:obj.selectList
				});
			}
		}
		// update scroll function
		var orig = jcf.modules.select.prototype.scrollToItem;
		jcf.modules.select.prototype.scrollToItem = function(){
			orig.apply(this);
			if(this.jcfScrollable) {
				this.jcfScrollable.refreshState();
			}
		}
	},
	extendTextarea: function() {
		// add scrollable if needed on control ready
		jcf.modules.textarea.prototype.onControlReady = function(obj){
			obj.jcfScrollable = new jcf.modules.customscroll({
				alwaysKeepScrollbars: true,
				alwaysPreventWheel: true,
				replaces: obj.realElement
			});
		}
		// update scroll function
		var orig = jcf.modules.textarea.prototype.refreshState;
		jcf.modules.textarea.prototype.refreshState = function(){
			orig.apply(this);
			if(this.jcfScrollable) {
				this.jcfScrollable.refreshState();
			}
		}
	},
	extendSelectMultiple: function(){
		// add scrollable if needed on control ready
		jcf.modules.selectmultiple.prototype.onControlReady = function(obj){
			//if(obj.optionsHolder.scrollHeight > obj.optionsHolder.offsetHeight) {
				obj.jcfScrollable = new jcf.modules.customscroll({
					alwaysPreventWheel: true,
					replaces:obj.optionsHolder
				});
			//}
		}
		// update scroll function
		var orig = jcf.modules.selectmultiple.prototype.scrollToItem;
		jcf.modules.selectmultiple.prototype.scrollToItem = function(){
			orig.apply(this);
			if(this.jcfScrollable) {
				this.jcfScrollable.refreshState();
			}
		}

		// update scroll size?
		var orig2 = jcf.modules.selectmultiple.prototype.rebuildOptions;
		jcf.modules.selectmultiple.prototype.rebuildOptions = function(){
			orig2.apply(this);
			if(this.jcfScrollable) {
				this.jcfScrollable.refreshState();
			}
		}

	}
});

// scrollbar plugin
jcf.addPlugin({
	name: 'scrollbar',
	defaultOptions: {
		size: 0,
		range: 0,
		moveStep: 6,
		moveDistance: 50,
		moveInterval: 10,
		trackHoldDelay: 900,
		holder: null,
		vertical: true,
		scrollTag: 'div',
		onScroll: function(){},
		onScrollEnd: function(){},
		onScrollStart: function(){},
		VscrollBarClass:'vscrollbar',
		VscrollStructure: '<div class="vscroll-up"></div><div class="vscroll-line"><div class="vscroll-slider"><div class="scroll-bar-top"></div><div class="scroll-bar-bottom"></div></div></div></div><div class="vscroll-down"></div>',
		VscrollTrack: 'div.vscroll-line',
		VscrollBtnDecClass:'div.vscroll-up',
		VscrollBtnIncClass:'div.vscroll-down',
		VscrollSliderClass:'div.vscroll-slider',
		HscrollBarClass:'hscrollbar',
		HscrollStructure: '<div class="hscroll-left"></div><div class="hscroll-line"><div class="hscroll-slider"><div class="scroll-bar-left"></div><div class="scroll-bar-right"></div></div></div></div><div class="hscroll-right"></div>',
		HscrollTrack: 'div.hscroll-line',
		HscrollBtnDecClass:'div.hscroll-left',
		HscrollBtnIncClass:'div.hscroll-right',
		HscrollSliderClass:'div.hscroll-slider'
	},
	init: function(userOptions) {
		this.setOptions(userOptions);
		this.createScrollBar();
		this.attachEvents();
		this.setSize();
	},
	setOptions: function(extOptions) {
		// merge options
		this.options = jcf.lib.extend({}, this.defaultOptions, extOptions);
		this.isVertical = this.options.vertical;
		this.prefix = this.isVertical ? 'V' : 'H';
		this.eventPageOffsetProperty = this.isVertical ? 'pageY' : 'pageX';
		this.positionProperty = this.isVertical ? 'top' : 'left';
		this.sizeProperty = this.isVertical ? 'height' : 'width';
		this.dimenionsProperty = this.isVertical ? 'offsetHeight' : 'offsetWidth';
		this.invertedDimenionsProperty = !this.isVertical ? 'offsetHeight' : 'offsetWidth';

		// set corresponding classes
		for(var p in this.options) {
			if(p.indexOf(this.prefix) == 0) {
				this.options[p.substr(1)] = this.options[p];
			}
		}
	},
	createScrollBar: function() {
		// create dimensions
		this.scrollBar = document.createElement(this.options.scrollTag);
		this.scrollBar.className = this.options.scrollBarClass;
		this.scrollBar.innerHTML = this.options.scrollStructure;

		// get elements
		this.track = jcf.lib.queryBySelector(this.options.scrollTrack,this.scrollBar)[0];
		this.btnDec = jcf.lib.queryBySelector(this.options.scrollBtnDecClass,this.scrollBar)[0];
		this.btnInc = jcf.lib.queryBySelector(this.options.scrollBtnIncClass,this.scrollBar)[0];
		this.slider = jcf.lib.queryBySelector(this.options.scrollSliderClass,this.scrollBar)[0];
	},
	attachEvents: function() {
		// append scrollbar to holder if provided
		if(this.options.holder) {
			this.options.holder.appendChild(this.scrollBar);
		}

		// attach listeners for slider and buttons
		jcf.lib.event.add(this.slider, jcf.eventPress, this.onSliderPressed, this);
		jcf.lib.event.add(this.btnDec, jcf.eventPress, this.onBtnDecPressed, this);
		jcf.lib.event.add(this.btnInc, jcf.eventPress, this.onBtnIncPressed, this);
		jcf.lib.event.add(this.track, jcf.eventPress, this.onTrackPressed, this);
	},
	setSize: function(value) {
		if(typeof value === 'number') {
			this.options.size = value;
		}
		this.scrollOffset = this.scrollValue = this.sliderOffset = 0;
		this.scrollBar.style[this.sizeProperty] = this.options.size + 'px';
		this.resizeControls();
		this.refreshSlider();
	},
	setRange: function(r) {
		this.options.range = Math.max(r,0);
		this.resizeControls();
	},
	doScrollWheelStep: function(direction) {
		// 1 - scroll up, -1 scroll down
		this.startScroll();
		if((direction < 0 && !this.isEndPosition()) || (direction > 0 && !this.isStartPosition())) {
			this.scrollTo(this.getScrollValue()-this.options.moveDistance * direction);
			this.moveScroll();
			this.endScroll();
			return false;
		}
	},
	resizeControls: function() {
		// calculate dimensions
		this.barSize = this.scrollBar[this.dimenionsProperty];
		this.btnDecSize = this.btnDec[this.dimenionsProperty];
		this.btnIncSize = this.btnInc[this.dimenionsProperty];
		this.trackSize = this.barSize - this.btnDecSize - this.btnIncSize;

		// resize and reposition elements
		this.track.style[this.sizeProperty] = this.trackSize + 'px';
		this.trackSize = this.track[this.dimenionsProperty];
		this.sliderSize = this.getSliderSize();
		this.slider.style[this.sizeProperty] = this.sliderSize + 'px';
		this.sliderSize = this.slider[this.dimenionsProperty];
	},
	refreshSlider: function(complete) {
		// refresh dimensions
		if(complete) {
			this.resizeControls();
		}
		// redraw slider and classes
		this.sliderOffset = isNaN(this.sliderOffset) ? 0 : this.sliderOffset;
		this.slider.style[this.positionProperty] = this.sliderOffset + 'px';
	},
	startScroll: function() {
		// refresh range if possible
		if(this.options.spawnClass && typeof this.options.spawnClass.getCurrentRange === 'function') {
			this.setRange(this.options.spawnClass.getCurrentRange(this));
		}
		this.resizeControls();
		this.scrollBarOffset = jcf.lib.getOffset(this.track)[this.positionProperty];
		this.options.onScrollStart();
	},
	moveScroll: function() {
		this.options.onScroll(this.scrollValue);
	},
	endScroll: function() {
		this.options.onScrollEnd();
	},
	startButtonMoveScroll: function(direction) {
		this.startScroll();
		clearInterval(this.buttonScrollTimer);
		this.buttonScrollTimer = setInterval(jcf.lib.bind(function(){
			this.scrollValue += this.options.moveStep * direction
			if(this.scrollValue > this.options.range) {
				this.scrollValue = this.options.range;
				this.endButtonMoveScroll();
			} else if(this.scrollValue < 0) {
				this.scrollValue = 0;
				this.endButtonMoveScroll();
			}
			this.scrollTo(this.scrollValue);

		},this),this.options.moveInterval);
	},
	endButtonMoveScroll: function() {
		clearInterval(this.buttonScrollTimer);
		this.endScroll();
	},
	isStartPosition: function() {
		return this.scrollValue === 0;
	},
	isEndPosition: function() {
		return this.scrollValue === this.options.range;
	},
	getSliderSize: function() {
		return Math.round(this.getSliderSizePercent() * this.trackSize / 100);
	},
	getSliderSizePercent: function() {
		return this.options.range === 0 ? 0 : this.barSize * 100 / (this.barSize + this.options.range);
	},
	getSliderOffsetByScrollValue: function() {
		return (this.scrollValue * 100 / this.options.range) * (this.trackSize - this.sliderSize) / 100;
	},
	getSliderOffsetPercent: function() {
		return this.sliderOffset * 100 / (this.trackSize - this.sliderSize);
	},
	getScrollValueBySliderOffset: function() {
		return this.getSliderOffsetPercent() * this.options.range / 100;
	},
	getScrollBarSize: function() {
		return this.scrollBar[this.invertedDimenionsProperty];
	},
	getScrollValue: function() {
		return this.scrollValue || 0;
	},
	scrollOnePage: function(direction) {
		this.scrollTo(this.scrollValue + direction*this.barSize);
	},
	scrollTo: function(x) {
		this.scrollValue = x < 0 ? 0 : x > this.options.range ? this.options.range : x;
		this.sliderOffset = this.getSliderOffsetByScrollValue();
		this.refreshSlider();
		this.moveScroll();
	},
	onSliderPressed: function(e){
		jcf.lib.event.add(document.body, jcf.eventRelease, this.onSliderRelease, this);
		jcf.lib.event.add(document.body, jcf.eventMove, this.onSliderMove, this);
		jcf.lib.disableTextSelection(this.slider);

		// calculate offsets once
		this.sliderInnerOffset = (jcf.isTouchDevice ? e.changedTouches[0] : e)[this.eventPageOffsetProperty] - jcf.lib.getOffset(this.slider)[this.positionProperty];
		this.startScroll();
		return false;
	},
	onSliderRelease: function(){
		jcf.lib.event.remove(document.body, jcf.eventRelease, this.onSliderRelease);
		jcf.lib.event.remove(document.body, jcf.eventMove, this.onSliderMove);
	},
	onSliderMove: function(e) {
		this.sliderOffset = (jcf.isTouchDevice ? e.changedTouches[0] : e)[this.eventPageOffsetProperty] - this.scrollBarOffset - this.sliderInnerOffset;
		if(this.sliderOffset < 0) {
			this.sliderOffset = 0;
		} else if(this.sliderOffset + this.sliderSize > this.trackSize) {
			this.sliderOffset = this.trackSize - this.sliderSize;
		}
		if(this.previousOffset != this.sliderOffset) {
			this.previousOffset = this.sliderOffset;
			this.scrollTo(this.getScrollValueBySliderOffset());
		}
	},
	onBtnIncPressed: function() {
		jcf.lib.event.add(document.body, jcf.eventRelease, this.onBtnIncRelease, this);
		jcf.lib.disableTextSelection(this.btnInc);
		this.startButtonMoveScroll(1);
		return false;
	},
	onBtnIncRelease: function() {
		jcf.lib.event.remove(document.body, jcf.eventRelease, this.onBtnIncRelease);
		this.endButtonMoveScroll();
	},
	onBtnDecPressed: function() {
		jcf.lib.event.add(document.body, jcf.eventRelease, this.onBtnDecRelease, this);
		jcf.lib.disableTextSelection(this.btnDec);
		this.startButtonMoveScroll(-1);
		return false;
	},
	onBtnDecRelease: function() {
		jcf.lib.event.remove(document.body, jcf.eventRelease, this.onBtnDecRelease);
		this.endButtonMoveScroll();
	},
	onTrackPressed: function(e) {
		var position = e[this.eventPageOffsetProperty] - jcf.lib.getOffset(this.track)[this.positionProperty];
		var direction = position < this.sliderOffset ? -1 : position > this.sliderOffset + this.sliderSize ? 1 : 0;
		if(direction) {
			this.scrollOnePage(direction);
		}
	}
});

// MooTools: the javascript framework.
// Load this file's selection again by visiting: http://mootools.net/more/1b84f78e3952c74d74d3e2d3be481364
// Or build this file again with packager using: packager build More/Fx.Scroll
/*
---
copyrights:
  - [MooTools](http://mootools.net)

licenses:
  - [MIT License](http://mootools.net/license.txt)
...
*/
MooTools.More={version:"1.4.0.1",build:"a4244edf2aa97ac8a196fc96082dd35af1abab87"};(function(){Fx.Scroll=new Class({Extends:Fx,options:{offset:{x:0,y:0},wheelStops:true},initialize:function(c,b){this.element=this.subject=document.id(c);
this.parent(b);if(typeOf(this.element)!="element"){this.element=document.id(this.element.getDocument().body);}if(this.options.wheelStops){var d=this.element,e=this.cancel.pass(false,this);
this.addEvent("start",function(){d.addEvent("mousewheel",e);},true);this.addEvent("complete",function(){d.removeEvent("mousewheel",e);},true);}},set:function(){var b=Array.flatten(arguments);
if(Browser.firefox){b=[Math.round(b[0]),Math.round(b[1])];}this.element.scrollTo(b[0],b[1]);return this;},compute:function(d,c,b){return[0,1].map(function(e){return Fx.compute(d[e],c[e],b);
});},start:function(c,d){if(!this.check(c,d)){return this;}var b=this.element.getScroll();return this.parent([b.x,b.y],[c,d]);},calculateScroll:function(g,f){var d=this.element,b=d.getScrollSize(),h=d.getScroll(),j=d.getSize(),c=this.options.offset,i={x:g,y:f};
for(var e in i){if(!i[e]&&i[e]!==0){i[e]=h[e];}if(typeOf(i[e])!="number"){i[e]=b[e]-j[e];}i[e]+=c[e];}return[i.x,i.y];},toTop:function(){return this.start.apply(this,this.calculateScroll(false,0));
},toLeft:function(){return this.start.apply(this,this.calculateScroll(0,false));},toRight:function(){return this.start.apply(this,this.calculateScroll("right",false));
},toBottom:function(){return this.start.apply(this,this.calculateScroll(false,"bottom"));},toElement:function(d,e){e=e?Array.from(e):["x","y"];var c=a(this.element)?{x:0,y:0}:this.element.getScroll();
var b=Object.map(document.id(d).getPosition(this.element),function(g,f){return e.contains(f)?g+c[f]:false;});return this.start.apply(this,this.calculateScroll(b.x,b.y));
},toElementEdge:function(d,g,e){g=g?Array.from(g):["x","y"];d=document.id(d);var i={},f=d.getPosition(this.element),j=d.getSize(),h=this.element.getScroll(),b=this.element.getSize(),c={x:f.x+j.x,y:f.y+j.y};
["x","y"].each(function(k){if(g.contains(k)){if(c[k]>h[k]+b[k]){i[k]=c[k]-b[k];}if(f[k]<h[k]){i[k]=f[k];}}if(i[k]==null){i[k]=h[k];}if(e&&e[k]){i[k]=i[k]+e[k];
}},this);if(i.x!=h.x||i.y!=h.y){this.start(i.x,i.y);}return this;},toElementCenter:function(e,f,h){f=f?Array.from(f):["x","y"];e=document.id(e);var i={},c=e.getPosition(this.element),d=e.getSize(),b=this.element.getScroll(),g=this.element.getSize();
["x","y"].each(function(j){if(f.contains(j)){i[j]=c[j]-(g[j]-d[j])/2;}if(i[j]==null){i[j]=b[j];}if(h&&h[j]){i[j]=i[j]+h[j];}},this);if(i.x!=b.x||i.y!=b.y){this.start(i.x,i.y);
}return this;}});function a(b){return(/^(?:body|html)$/i).test(b.tagName);}})();

// iepp v2.1pre @jon_neal & @aFarkas github.com/aFarkas/iepp
// html5shiv @rem remysharp.com/html5-enabling-script
// Dual licensed under the MIT or GPL Version 2 licenses
/*@cc_on(function(a,b){function r(a){var b=-1;while(++b<f)a.createElement(e[b])}if(!window.attachEvent||!b.createStyleSheet||!function(){var a=document.createElement("div");return a.innerHTML="<elem></elem>",a.childNodes.length!==1}())return;a.iepp=a.iepp||{};var c=a.iepp,d=c.html5elements||"abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|subline|summary|time|video",e=d.split("|"),f=e.length,g=new RegExp("(^|\\s)("+d+")","gi"),h=new RegExp("<(/*)("+d+")","gi"),i=/^\s*[\{\}]\s*$/,j=new RegExp("(^|[^\\n]*?\\s)("+d+")([^\\n]*)({[\\n\\w\\W]*?})","gi"),k=b.createDocumentFragment(),l=b.documentElement,m=b.getElementsByTagName("script")[0].parentNode,n=b.createElement("body"),o=b.createElement("style"),p=/print|all/,q;c.getCSS=function(a,b){try{if(a+""===undefined)return""}catch(d){return""}var e=-1,f=a.length,g,h=[];while(++e<f){g=a[e];if(g.disabled)continue;b=g.media||b,p.test(b)&&h.push(c.getCSS(g.imports,b),g.cssText),b="all"}return h.join("")},c.parseCSS=function(a){var b=[],c;while((c=j.exec(a))!=null)b.push(((i.exec(c[1])?"\n":c[1])+c[2]+c[3]).replace(g,"$1.iepp-$2")+c[4]);return b.join("\n")},c.writeHTML=function(){var a=-1;q=q||b.body;while(++a<f){var c=b.getElementsByTagName(e[a]),d=c.length,g=-1;while(++g<d)c[g].className.indexOf("iepp-")<0&&(c[g].className+=" iepp-"+e[a])}k.appendChild(q),l.appendChild(n),n.className=q.className,n.id=q.id,n.innerHTML=q.innerHTML.replace(h,"<$1font")},c._beforePrint=function(){if(c.disablePP)return;o.styleSheet.cssText=c.parseCSS(c.getCSS(b.styleSheets,"all")),c.writeHTML()},c.restoreHTML=function(){if(c.disablePP)return;n.swapNode(q)},c._afterPrint=function(){c.restoreHTML(),o.styleSheet.cssText=""},r(b),r(k);if(c.disablePP)return;m.insertBefore(o,m.firstChild),o.media="print",o.className="iepp-printshim",a.attachEvent("onbeforeprint",c._beforePrint),a.attachEvent("onafterprint",c._afterPrint)})(this,document)@*/

function onLoadTicket() {
	if(typeof s3FlashUploadTicket != 'undefined')
	{
		fileUploadSwitcherTicket = new fileUploadSwitcher('ticket', s3FlashUploadTicket);
	}
}

function onErrorTicket(file, error, info) {
	enableButtonTicketSubmit();
	fileUploadSwitcherTicket.switchToStandardTicketUploader();
	var message = {file: file.name};
}

function onLoadReply() {
	if(typeof s3FlashUploadReply != 'undefined')
	{
		fileUploadSwitcherReply = new fileUploadSwitcher('reply', s3FlashUploadReply);
	}
}

function fixClientAreaPagination()
{
	var pager = $$('footer.btn-holder div.paging-area ul li');
	if(!pager.length) return;
	var prev = pager[0];
	var next = pager[pager.length - 1];
	if(!prev.hasClass('paging-btn'))
	{
		prev.addClass('paging-btn');
	}
	if(!next.hasClass('paging-btn'))
	{
		next.addClass('paging-btn');
	}
}

window.addEvent('domready', function() {
	$$('form.add-order-form').each(function(curForm){
		new TicketPage({
			form: curForm,
			bannerData: [
				{
					width: 728,
					height: 90,
					isRounded: false,
					isAnimated: false,
					isPsd: false
				}
			]
		});
	});

	fixClientAreaPagination();
});


/*	SWFObject v2.2 <http://code.google.com/p/swfobject/> 
	is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> 
*/
var swfobject=function(){var D="undefined",r="object",S="Shockwave Flash",W="ShockwaveFlash.ShockwaveFlash",q="application/x-shockwave-flash",R="SWFObjectExprInst",x="onreadystatechange",O=window,j=document,t=navigator,T=false,U=[h],o=[],N=[],I=[],l,Q,E,B,J=false,a=false,n,G,m=true,M=function(){var aa=typeof j.getElementById!=D&&typeof j.getElementsByTagName!=D&&typeof j.createElement!=D,ah=t.userAgent.toLowerCase(),Y=t.platform.toLowerCase(),ae=Y?/win/.test(Y):/win/.test(ah),ac=Y?/mac/.test(Y):/mac/.test(ah),af=/webkit/.test(ah)?parseFloat(ah.replace(/^.*webkit\/(\d+(\.\d+)?).*$/,"$1")):false,X=!+"\v1",ag=[0,0,0],ab=null;if(typeof t.plugins!=D&&typeof t.plugins[S]==r){ab=t.plugins[S].description;if(ab&&!(typeof t.mimeTypes!=D&&t.mimeTypes[q]&&!t.mimeTypes[q].enabledPlugin)){T=true;X=false;ab=ab.replace(/^.*\s+(\S+\s+\S+$)/,"$1");ag[0]=parseInt(ab.replace(/^(.*)\..*$/,"$1"),10);ag[1]=parseInt(ab.replace(/^.*\.(.*)\s.*$/,"$1"),10);ag[2]=/[a-zA-Z]/.test(ab)?parseInt(ab.replace(/^.*[a-zA-Z]+(.*)$/,"$1"),10):0}}else{if(typeof O.ActiveXObject!=D){try{var ad=new ActiveXObject(W);if(ad){ab=ad.GetVariable("$version");if(ab){X=true;ab=ab.split(" ")[1].split(",");ag=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}}catch(Z){}}}return{w3:aa,pv:ag,wk:af,ie:X,win:ae,mac:ac}}(),k=function(){if(!M.w3){return}if((typeof j.readyState!=D&&j.readyState=="complete")||(typeof j.readyState==D&&(j.getElementsByTagName("body")[0]||j.body))){f()}if(!J){if(typeof j.addEventListener!=D){j.addEventListener("DOMContentLoaded",f,false)}if(M.ie&&M.win){j.attachEvent(x,function(){if(j.readyState=="complete"){j.detachEvent(x,arguments.callee);f()}});if(O==top){(function(){if(J){return}try{j.documentElement.doScroll("left")}catch(X){setTimeout(arguments.callee,0);return}f()})()}}if(M.wk){(function(){if(J){return}if(!/loaded|complete/.test(j.readyState)){setTimeout(arguments.callee,0);return}f()})()}s(f)}}();function f(){if(J){return}try{var Z=j.getElementsByTagName("body")[0].appendChild(C("span"));Z.parentNode.removeChild(Z)}catch(aa){return}J=true;var X=U.length;for(var Y=0;Y<X;Y++){U[Y]()}}function K(X){if(J){X()}else{U[U.length]=X}}function s(Y){if(typeof O.addEventListener!=D){O.addEventListener("load",Y,false)}else{if(typeof j.addEventListener!=D){j.addEventListener("load",Y,false)}else{if(typeof O.attachEvent!=D){i(O,"onload",Y)}else{if(typeof O.onload=="function"){var X=O.onload;O.onload=function(){X();Y()}}else{O.onload=Y}}}}}function h(){if(T){V()}else{H()}}function V(){var X=j.getElementsByTagName("body")[0];var aa=C(r);aa.setAttribute("type",q);var Z=X.appendChild(aa);if(Z){var Y=0;(function(){if(typeof Z.GetVariable!=D){var ab=Z.GetVariable("$version");if(ab){ab=ab.split(" ")[1].split(",");M.pv=[parseInt(ab[0],10),parseInt(ab[1],10),parseInt(ab[2],10)]}}else{if(Y<10){Y++;setTimeout(arguments.callee,10);return}}X.removeChild(aa);Z=null;H()})()}else{H()}}function H(){var ag=o.length;if(ag>0){for(var af=0;af<ag;af++){var Y=o[af].id;var ab=o[af].callbackFn;var aa={success:false,id:Y};if(M.pv[0]>0){var ae=c(Y);if(ae){if(F(o[af].swfVersion)&&!(M.wk&&M.wk<312)){w(Y,true);if(ab){aa.success=true;aa.ref=z(Y);ab(aa)}}else{if(o[af].expressInstall&&A()){var ai={};ai.data=o[af].expressInstall;ai.width=ae.getAttribute("width")||"0";ai.height=ae.getAttribute("height")||"0";if(ae.getAttribute("class")){ai.styleclass=ae.getAttribute("class")}if(ae.getAttribute("align")){ai.align=ae.getAttribute("align")}var ah={};var X=ae.getElementsByTagName("param");var ac=X.length;for(var ad=0;ad<ac;ad++){if(X[ad].getAttribute("name").toLowerCase()!="movie"){ah[X[ad].getAttribute("name")]=X[ad].getAttribute("value")}}P(ai,ah,Y,ab)}else{p(ae);if(ab){ab(aa)}}}}}else{w(Y,true);if(ab){var Z=z(Y);if(Z&&typeof Z.SetVariable!=D){aa.success=true;aa.ref=Z}ab(aa)}}}}}function z(aa){var X=null;var Y=c(aa);if(Y&&Y.nodeName=="OBJECT"){if(typeof Y.SetVariable!=D){X=Y}else{var Z=Y.getElementsByTagName(r)[0];if(Z){X=Z}}}return X}function A(){return !a&&F("6.0.65")&&(M.win||M.mac)&&!(M.wk&&M.wk<312)}function P(aa,ab,X,Z){a=true;E=Z||null;B={success:false,id:X};var ae=c(X);if(ae){if(ae.nodeName=="OBJECT"){l=g(ae);Q=null}else{l=ae;Q=X}aa.id=R;if(typeof aa.width==D||(!/%$/.test(aa.width)&&parseInt(aa.width,10)<310)){aa.width="310"}if(typeof aa.height==D||(!/%$/.test(aa.height)&&parseInt(aa.height,10)<137)){aa.height="137"}j.title=j.title.slice(0,47)+" - Flash Player Installation";var ad=M.ie&&M.win?"ActiveX":"PlugIn",ac="MMredirectURL="+O.location.toString().replace(/&/g,"%26")+"&MMplayerType="+ad+"&MMdoctitle="+j.title;if(typeof ab.flashvars!=D){ab.flashvars+="&"+ac}else{ab.flashvars=ac}if(M.ie&&M.win&&ae.readyState!=4){var Y=C("div");X+="SWFObjectNew";Y.setAttribute("id",X);ae.parentNode.insertBefore(Y,ae);ae.style.display="none";(function(){if(ae.readyState==4){ae.parentNode.removeChild(ae)}else{setTimeout(arguments.callee,10)}})()}u(aa,ab,X)}}function p(Y){if(M.ie&&M.win&&Y.readyState!=4){var X=C("div");Y.parentNode.insertBefore(X,Y);X.parentNode.replaceChild(g(Y),X);Y.style.display="none";(function(){if(Y.readyState==4){Y.parentNode.removeChild(Y)}else{setTimeout(arguments.callee,10)}})()}else{Y.parentNode.replaceChild(g(Y),Y)}}function g(ab){var aa=C("div");if(M.win&&M.ie){aa.innerHTML=ab.innerHTML}else{var Y=ab.getElementsByTagName(r)[0];if(Y){var ad=Y.childNodes;if(ad){var X=ad.length;for(var Z=0;Z<X;Z++){if(!(ad[Z].nodeType==1&&ad[Z].nodeName=="PARAM")&&!(ad[Z].nodeType==8)){aa.appendChild(ad[Z].cloneNode(true))}}}}}return aa}function u(ai,ag,Y){var X,aa=c(Y);if(M.wk&&M.wk<312){return X}if(aa){if(typeof ai.id==D){ai.id=Y}if(M.ie&&M.win){var ah="";for(var ae in ai){if(ai[ae]!=Object.prototype[ae]){if(ae.toLowerCase()=="data"){ag.movie=ai[ae]}else{if(ae.toLowerCase()=="styleclass"){ah+=' class="'+ai[ae]+'"'}else{if(ae.toLowerCase()!="classid"){ah+=" "+ae+'="'+ai[ae]+'"'}}}}}var af="";for(var ad in ag){if(ag[ad]!=Object.prototype[ad]){af+='<param name="'+ad+'" value="'+ag[ad]+'" />'}}aa.outerHTML='<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"'+ah+">"+af+"</object>";N[N.length]=ai.id;X=c(ai.id)}else{var Z=C(r);Z.setAttribute("type",q);for(var ac in ai){if(ai[ac]!=Object.prototype[ac]){if(ac.toLowerCase()=="styleclass"){Z.setAttribute("class",ai[ac])}else{if(ac.toLowerCase()!="classid"){Z.setAttribute(ac,ai[ac])}}}}for(var ab in ag){if(ag[ab]!=Object.prototype[ab]&&ab.toLowerCase()!="movie"){e(Z,ab,ag[ab])}}aa.parentNode.replaceChild(Z,aa);X=Z}}return X}function e(Z,X,Y){var aa=C("param");aa.setAttribute("name",X);aa.setAttribute("value",Y);Z.appendChild(aa)}function y(Y){var X=c(Y);if(X&&X.nodeName=="OBJECT"){if(M.ie&&M.win){X.style.display="none";(function(){if(X.readyState==4){b(Y)}else{setTimeout(arguments.callee,10)}})()}else{X.parentNode.removeChild(X)}}}function b(Z){var Y=c(Z);if(Y){for(var X in Y){if(typeof Y[X]=="function"){Y[X]=null}}Y.parentNode.removeChild(Y)}}function c(Z){var X=null;try{X=j.getElementById(Z)}catch(Y){}return X}function C(X){return j.createElement(X)}function i(Z,X,Y){Z.attachEvent(X,Y);I[I.length]=[Z,X,Y]}function F(Z){var Y=M.pv,X=Z.split(".");X[0]=parseInt(X[0],10);X[1]=parseInt(X[1],10)||0;X[2]=parseInt(X[2],10)||0;return(Y[0]>X[0]||(Y[0]==X[0]&&Y[1]>X[1])||(Y[0]==X[0]&&Y[1]==X[1]&&Y[2]>=X[2]))?true:false}function v(ac,Y,ad,ab){if(M.ie&&M.mac){return}var aa=j.getElementsByTagName("head")[0];if(!aa){return}var X=(ad&&typeof ad=="string")?ad:"screen";if(ab){n=null;G=null}if(!n||G!=X){var Z=C("style");Z.setAttribute("type","text/css");Z.setAttribute("media",X);n=aa.appendChild(Z);if(M.ie&&M.win&&typeof j.styleSheets!=D&&j.styleSheets.length>0){n=j.styleSheets[j.styleSheets.length-1]}G=X}if(M.ie&&M.win){if(n&&typeof n.addRule==r){n.addRule(ac,Y)}}else{if(n&&typeof j.createTextNode!=D){n.appendChild(j.createTextNode(ac+" {"+Y+"}"))}}}function w(Z,X){if(!m){return}var Y=X?"visible":"hidden";if(J&&c(Z)){c(Z).style.visibility=Y}else{v("#"+Z,"visibility:"+Y)}}function L(Y){var Z=/[\\\"<>\.;]/;var X=Z.exec(Y)!=null;return X&&typeof encodeURIComponent!=D?encodeURIComponent(Y):Y}var d=function(){if(M.ie&&M.win){window.attachEvent("onunload",function(){var ac=I.length;for(var ab=0;ab<ac;ab++){I[ab][0].detachEvent(I[ab][1],I[ab][2])}var Z=N.length;for(var aa=0;aa<Z;aa++){y(N[aa])}for(var Y in M){M[Y]=null}M=null;for(var X in swfobject){swfobject[X]=null}swfobject=null})}}();return{registerObject:function(ab,X,aa,Z){if(M.w3&&ab&&X){var Y={};Y.id=ab;Y.swfVersion=X;Y.expressInstall=aa;Y.callbackFn=Z;o[o.length]=Y;w(ab,false)}else{if(Z){Z({success:false,id:ab})}}},getObjectById:function(X){if(M.w3){return z(X)}},embedSWF:function(ab,ah,ae,ag,Y,aa,Z,ad,af,ac){var X={success:false,id:ah};if(M.w3&&!(M.wk&&M.wk<312)&&ab&&ah&&ae&&ag&&Y){w(ah,false);K(function(){ae+="";ag+="";var aj={};if(af&&typeof af===r){for(var al in af){aj[al]=af[al]}}aj.data=ab;aj.width=ae;aj.height=ag;var am={};if(ad&&typeof ad===r){for(var ak in ad){am[ak]=ad[ak]}}if(Z&&typeof Z===r){for(var ai in Z){if(typeof am.flashvars!=D){am.flashvars+="&"+ai+"="+Z[ai]}else{am.flashvars=ai+"="+Z[ai]}}}if(F(Y)){var an=u(aj,am,ah);if(aj.id==ah){w(ah,true)}X.success=true;X.ref=an}else{if(aa&&A()){aj.data=aa;P(aj,am,ah,ac);return}else{w(ah,true)}}if(ac){ac(X)}})}else{if(ac){ac(X)}}},switchOffAutoHideShow:function(){m=false},ua:M,getFlashPlayerVersion:function(){return{major:M.pv[0],minor:M.pv[1],release:M.pv[2]}},hasFlashPlayerVersion:F,createSWF:function(Z,Y,X){if(M.w3){return u(Z,Y,X)}else{return undefined}},showExpressInstall:function(Z,aa,X,Y){if(M.w3&&A()){P(Z,aa,X,Y)}},removeSWF:function(X){if(M.w3){y(X)}},createCSS:function(aa,Z,Y,X){if(M.w3){v(aa,Z,Y,X)}},addDomLoadEvent:K,addLoadEvent:s,getQueryParamValue:function(aa){var Z=j.location.search||j.location.hash;if(Z){if(/\?/.test(Z)){Z=Z.split("?")[1]}if(aa==null){return L(Z)}var Y=Z.split("&");for(var X=0;X<Y.length;X++){if(Y[X].substring(0,Y[X].indexOf("="))==aa){return L(Y[X].substring((Y[X].indexOf("=")+1)))}}}return""},expressInstallCallback:function(){if(a){var X=c(R);if(X&&l){X.parentNode.replaceChild(l,X);if(Q){w(Q,true);if(M.ie&&M.win){l.style.display="block"}}if(E){E(B)}}a=false}}}}();

function onLoadOrder() {
	if(typeof s3FlashUploadOrder != 'undefined')
	{
		fileUploadSwitcherOrder = new fileUploadSwitcher('order', s3FlashUploadOrder);
	}
}

function initOrderPage(bannerList) {
	$$('form.order-form').each(function(curForm){
		new OrderPage({
			form: curForm,
			bannerData: bannerList
		});
	});
}

function repositionOrderForm()
{
	try
	{
		s3FlashUploadOrder.reposition();
	}
	catch(e){}
}

window.addEvent('domready', function() {
	if(typeof initBannerList != "object")
	{
		initBannerList = [
			{
				width: 728,
				height: 90
			},
			{
				width: 468,
				height: 60
			}
		];
	}
	initOrderPage(initBannerList);
	setGmtOffset('order-gmt-offset');
});


var MIMEtype = {

	mimetypes: {
		"ez": "application/andrew-inset",
		"hqx": "application/mac-binhex40",
		"cpt": "application/mac-compactpro",
		"doc": "application/msword",
		"oda": "application/oda",
		"pdf": "application/pdf",
		"ai": "application/postscript",
		"eps": "application/postscript",
		"ps": "application/postscript",
		"smi": "application/smil",
		"smil": "application/smil",
		"wbxml": "application/vnd.wap.wbxml",
		"wmlc": "application/vnd.wap.wmlc",
		"wmlsc": "application/vnd.wap.wmlscriptc",
		"bcpio": "application/x-bcpio",
		"vcd": "application/x-cdlink",
		"pgn": "application/x-chess-pgn",
		"cpio": "application/x-cpio",
		"csh": "application/x-csh",
		"dcr": "application/x-director",
		"dir": "application/x-director",
		"dxr": "application/x-director",
		"dvi": "application/x-dvi",
		"spl": "application/x-futuresplash",
		"gtar": "application/x-gtar",
		"hdf": "application/x-hdf",
		"js": "application/x-javascript",
		"skp": "application/x-koan",
		"skd": "application/x-koan",
		"skt": "application/x-koan",
		"skm": "application/x-koan",
		"latex": "application/x-latex",
		"nc": "application/x-netcdf",
		"cdf": "application/x-netcdf",
		"sh": "application/x-sh",
		"shar": "application/x-shar",
		"swf": "application/x-shockwave-flash",
		"sit": "application/x-stuffit",
		"sv4cpio": "application/x-sv4cpio",
		"sv4crc": "application/x-sv4crc",
		"tar": "application/x-tar",
		"tcl": "application/x-tcl",
		"tex": "application/x-tex",
		"texinfo": "application/x-texinfo",
		"texi": "application/x-texinfo",
		"t": "application/x-troff",
		"tr": "application/x-troff",
		"roff": "application/x-troff",
		"man": "application/x-troff-man",
		"me": "application/x-troff-me",
		"ms": "application/x-troff-ms",
		"ustar": "application/x-ustar",
		"src": "application/x-wais-source",
		"xhtml": "application/xhtml+xml",
		"xht": "application/xhtml+xml",
		"zip": "application/zip",
		"au": "audio/basic",
		"snd": "audio/basic",
		"mid": "audio/midi",
		"midi": "audio/midi",
		"kar": "audio/midi",
		"mpga": "audio/mpeg",
		"mp2": "audio/mpeg",
		"mp3": "audio/mpeg",
		"aif": "audio/x-aiff",
		"aiff": "audio/x-aiff",
		"aifc": "audio/x-aiff",
		"m3u": "audio/x-mpegurl",
		"ram": "audio/x-pn-realaudio",
		"rm": "audio/x-pn-realaudio",
		"rpm": "audio/x-pn-realaudio-plugin",
		"ra": "audio/x-realaudio",
		"wav": "audio/x-wav",
		"pdb": "chemical/x-pdb",
		"xyz": "chemical/x-xyz",
		"bmp": "image/bmp",
		"gif": "image/gif",
		"ief": "image/ief",
		"jpeg": "image/jpeg",
		"jpg": "image/jpeg",
		"jpe": "image/jpeg",
		"png": "image/png",
		"tiff": "image/tiff",
		"tif": "image/tif",
		"djvu": "image/vnd.djvu",
		"djv": "image/vnd.djvu",
		"wbmp": "image/vnd.wap.wbmp",
		"ras": "image/x-cmu-raster",
		"pnm": "image/x-portable-anymap",
		"pbm": "image/x-portable-bitmap",
		"pgm": "image/x-portable-graymap",
		"ppm": "image/x-portable-pixmap",
		"rgb": "image/x-rgb",
		"xbm": "image/x-xbitmap",
		"xpm": "image/x-xpixmap",
		"xwd": "image/x-windowdump",
		"igs": "model/iges",
		"iges": "model/iges",
		"msh": "model/mesh",
		"mesh": "model/mesh",
		"silo": "model/mesh",
		"wrl": "model/vrml",
		"vrml": "model/vrml",
		"css": "text/css",
		"html": "text/html",
		"htm": "text/html",
		"asc": "text/plain",
		"txt": "text/plain",
		"rtx": "text/richtext",
		"rtf": "text/rtf",
		"sgml": "text/sgml",
		"sgm": "text/sgml",
		"tsv": "text/tab-seperated-values",
		"wml": "text/vnd.wap.wml",
		"wmls": "text/vnd.wap.wmlscript",
		"etx": "text/x-setext",
		"xml": "text/xml",
		"xsl": "text/xml",
		"mpeg": "video/mpeg",
		"mpg": "video/mpeg",
		"mpe": "video/mpeg",
		"qt": "video/quicktime",
		"mov": "video/quicktime",
		"mxu": "video/vnd.mpegurl",
		"avi": "video/x-msvideo",
		"movie": "video/x-sgi-movie",
		"ice": "x-conference-xcooltalk"
	},

	getType: function(filename) {
		var parts = filename.split('.');
		var ext = parts[parts.length - 1].toLowerCase();

		if(this.mimetypes[ext]) {
			return this.mimetypes[ext];
		}
		else {
			return 'application/octet-stream';
		}
	}
};


/**
 * Fx.ProgressBar
 *
 * @version		1.0 with changes
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <mail [at] digitarald [dot] de>
 * @copyright	Authors
 */

Fx.ProgressBar = new Class({

	Extends: Fx,

	options: {
		text: null,
		transition: Fx.Transitions.Circ.easeOut,
		link: 'cancel'
	},

	initialize: function(element, options) {
		this.element = $(element);
		this.parent(options);
		this.text = $(this.options.text);
		this.set(0);
	},

	start: function(to, total) {
		return this.parent(this.now, (arguments.length == 1) ? to.limit(0, 100) : to / total * 100);
	},

	set: function(to) {
		this.now = to;
		this.element.setStyle('width', to + '%');
		if(this.text) {
			this.text.set('text', to == 100? 'please wait...': 'uploading: ' + Math.round(to) + '%');
		}

		return this;
	}
});


/**
 * Swiff.Uploader - Flash FileReference Control
 *
 * @version		1.2
 *
 * @license		MIT License
 *
 * @author		Harald Kirschner <mail [at] digitarald [dot] de>
 * @copyright	Authors
 */

Swiff.Uploader = new Class({

	Extends: Swiff,

	Implements: Events,

	options: {
		path: 'swiff.uploader.swf',
		multiple: true,
		queued: true,
		typeFilter: null,
		url: null,
		method: 'post',
		data: null,
		fieldName: 'Filedata',
		target: null,
		height: '100%',
		width: '100%',
		callBacks: null,
		params:{wMode:"transparent"}
	},

	initialize: function(options){
		if (Browser.Plugins.Flash.version < 9) return false;
		this.setOptions(options);

		this.loaded = false;

		var callBacks = this.options.callBacks || this;
		if (callBacks.onLoad) this.addEvent('onLoad', callBacks.onLoad);
		if (!callBacks.onBrowse) {
			callBacks.onBrowse = function() {
				return this.options.typeFilter;
			}
		}

		var prepare = {}, self = this;
		['onBrowse', 'onSelect', 'onAllSelect', 'onCancel', 'onBeforeOpen', 'onOpen', 'onProgress', 'onComplete', 'onError', 'onAllComplete'].each(function(index) {
			var fn = callBacks[index] || $empty;
			prepare[index] = function() {
				self.fireEvent(index, arguments, 10);
				return fn.apply(self, arguments);
			};
		});

		prepare.onLoad = this.load.create({delay: 10, bind: this});
		this.options.callBacks = prepare;

		var path = this.options.path;
		if(!path.contains('?')) {
			path += '?nocache=' + $time(); // quick fix
		}

		this.parent(path);

		var scroll = window.getScroll();
		this.box = new Element('div', {
			styles: {
				position: 'absolute',
				visibility: 'visible',
				zIndex: (this.options.id == 'nameContactFormSwiffy')?9999:999,
				overflow: 'hidden',
				height: 15,
				width: 15,
				top: scroll.y,
				left: scroll.x
			}
		});

		this.inject(this.box);
		this.box.inject($(this.options.container) || document.body);
		return this;
	},

	load: function(){
		this.remote('register', this.instance, this.options.multiple, this.options.queued);
		this.fireEvent('onLoad');

		this.target = $(this.options.target);
		if(this.target) {
			this.reposition();
			window.addEvent('resize', this.reposition.bind(this));
		}
		this.loaded = true;
	},

	reposition: function() {
		if(this.target) {
			var pos = this.target.getCoordinates(this.box.getOffsetParent());
			this.box.setStyles(pos);
		}
	},

	/*
	Method: browse
		Open the file browser.
	*/

	browse: function(typeFilter){
		if(this.loaded) {
			this.options.typeFilter = $pick(typeFilter, this.options.typeFilter);
			return this.remote('browse');
		}
		else {
			return false;
		}
	},

	/*
	Method: upload
		Starts the upload of all selected files.
	*/

	upload: function(options){
		if(this.loaded) {
			var current = this.options;
			options = $extend({data: current.data, url: current.url, method: current.method, fieldName: current.fieldName}, options);
			if ($type(options.data) == 'element') options.data = $(options.data).toQueryString();
			return this.remote('upload', options);
		}
		else {
			return false;
		}
	},

	/*
	Method: removeFile
		For multiple uploads cancels and removes the given file from queue.

	Arguments:
		name - (string) Filename
		name - (string) Filesize in byte
	*/

	removeFile: function(file){
		if(file) file = {name: file.name, size: file.size};
		return this.remote('removeFile', file);
	},

	/*
	Method: getFileList
		Returns one Array with with arrays containing name and size of the file.

	Returns:
		(array) An array with files
	*/

	getFileList: function(){
		return this.remote('getFileList');
	}

});


var Uploader = new Class({
	Extends: Swiff.Uploader,

	options: {
		limitSize: false,
		multiple: false,
		queued: false,
		instantStart: false,
		validateFile: $lambda(true), // provide a function that returns true for valid and false for invalid files.
		debug: false,
		fileInvalid: null, 					// called for invalid files with error stack as 2nd argument
		fileUpload: null, 					// called when file is opened for upload, allows to modify the upload options (2nd argument) for every upload
		fileComplete: null					// updates the file element to completed state and gets the response (2nd argument)
		/**
		 * Events:
		 * onBrowse, onSelect, onAllSelect, onCancel, onBeforeOpen, onOpen, onProgress, onComplete, onError, onAllComplete
		 */
	},

	initialize: function(status, options) {
		this.status = $(status);
		this.files = [];
		if(options.callBacks) {
			this.addEvents(options.callBacks);
			options.callBacks = null;
		}
		this.parent(options);
		this.render();
	},

	render: function() {
		var progress = new Element('span', {'class': 'overall-progress'}).inject(this.status);
		var text = new Element('span', {'class': 'progress-text'}).inject(progress, 'after');
		this.progressBar = new Fx.ProgressBar(progress, {text: text});
	},

	onLoad: function() {
		this.log('Uploader ready!');
	},

	onBeforeOpen: function(file, options) {
		this.log('Initialize upload for "{name}".', file);
		var fn = this.options.fileUpload;
		var obj = fn? fn.call(this, this.getFile(file), options): options;
		return obj;
	},

	onOpen: function(file, overall) {
		this.log('Starting upload "{name}".', file);
	},

	onProgress: function(file, current, overall) {
		this.progressBar.start(overall.bytesLoaded, overall.bytesTotal);
		this.log('Uploading "' + file.name + '" "' + overall.bytesLoaded + '": "' + overall.bytesTotal + '".');
	},

	onSelect: function(file) {
		var errors = [];
		if(this.options.limitSize && (file.size > this.options.limitSize)) {
			errors.push('size');
		}
		if(!this.options.validateFile.call(this, file, errors)) {
			errors.push('custom');
		}
		if(errors.length) {
			var fn = this.options.fileInvalid;
			if(fn) fn.call(this, file, errors);
			return false;
		}
		this.removeFile();
		this.files.push(file);
		return true;
	},

	onAllSelect: function(files, current, overall) {
		this.log('Added ' + files.length + ' files, now we have (' + current.bytesTotal + ' bytes).', arguments);
		if(this.files.length && this.options.instantStart) {
			this.upload.delay(10, this);
		}
	},

	onComplete: function(file, response) {
		this.log('Completed upload "' + file.name + '".', arguments);
		this.progressBar.start(100);
		var fn = this.options.fileComplete;
		if(fn) {
			fn.call(this, this.finishFile(file), response);
		}
	},

	onAllComplete: function(current) {
		this.log('Completed all files, ' + current.bytesTotal + ' bytes.', arguments);
		this.status.removeClass('file-uploading');
		this.progressBar.start(100);
	},

	onError: function(file, error, info) {
		this.log('Upload "' + file.name + '" failed. "{1}": "{2}".', arguments);
		this.status.removeClass('file-uploading');
		this.progressBar.cancel();
		var fn = this.options.fileError;
		if(fn) {
			fn.call(this, this.finishFile(file), error, info);
		}
		this.removeFile();
	},

	onCancel: function() {
		this.log('Filebrowser cancelled.', arguments);
	},

	upload: function(options) {
		var ret = this.parent(options);
		if(ret === true) {
			this.log('Upload started.');
			this.status.addClass('file-uploading');
			this.progressBar.set(0);
			return true;
		} else if(ret) {
			this.log('An error occured: ' + ret)
		}
		else {
			this.log('Upload in progress or nothing to upload.');
		}
		return false;
	},

	removeFile: function(file) {
		if(!file) {
			this.files.empty();
		} else {
			if(!file.element) {
				file = this.getFile(file);
			}
			this.files.erase(file);
		}
		this.parent(file);
	},

	getFile: function(file) {
		var ret = null;
		this.files.some(function(value) {
			if((value.name != file.name) || (value.size != file.size)) {
				return false;
			}
			ret = value;
			return true;
		});
		return ret;
	},

	finishFile: function(file) {
		file = this.getFile(file);
		file.finished = true;
		return file;
	},

	log: function(text, args) {
		if(this.options.debug && window.console) console.log(text.substitute(args || {}));
	}
})


var S3FlashUpload = new Class({
	Implements: [Options, Events],

	options: {
		form: null,
		progress: null,
		file: null,
		fakeFile: null,
		text: null,
		browse: null,
		s3BucketUri: null,
		s3Form: null,
		s3ContentType: null,
		s3FilePrefix: null,
		name: 'flashUpload',
		fieldName: 'fileName',
		maxUploadSize: 67108864,
		path: 'swiff.uploader.swf',
		messageEmptyUploadSize: 'Please upload only non-empty files.',
		messageMaxUploadSize: 'Please upload only files smaller than {maxUploadSize}.',
		messageUploadFailed: 'Upload "{file}" failed. The upload will switch to the Basic uploader.',
		onLoad: Class.empty,
		onSubmit: Class.empty,
		onUpload: Class.empty,
		onSelect: Class.empty,
		onSelectError: Class.empty,
		onError: Class.empty,
		onComplete: Class.empty,
		debug: false
	},

	initialize: function(options) {
		this.setOptions(options);
		if(!options.onSelectError) {
			this.addEvent('onSelectError', this.onSelectError);
		}
		if(!options.onError) {
			this.addEvent('onError', this.onError);
		}
		this.form = $(this.options.form);
		this.progress = $(this.options.progress);
		this.file = $(this.options.file);
		this.fakeFile = $(this.options.fakeFile);
		this.text = $(this.options.text);
		this.browse = $(this.options.browse);
		this.s3Form = $(this.options.s3Form);
		this.s3ContentType = $(this.options.s3ContentType);
		this.maxUploadSizeKB = this.sizeToKB(this.options.maxUploadSize);
		this.loaded = false;
		this.isStandardUploader = true;
		this.isFlashUploader = false;
		if(this.form && this.progress && this.file && this.fakeFile && this.text && this.browse && this.s3Form && this.s3ContentType) {
			this.activated = true;
			this.fileId = this.file.getProperty('id');
			this.fakeFile.setProperty('value', '');
			this.text.setProperty('value', '');
			this.text.setProperty('autocomplete', 'off');
			if(Browser.Plugins.Flash.version >= 9 && !(Browser.Engine.webkit419 || Browser.Engine.presto925)) {
				this.swiffy = new Uploader(this.progress, {
					url: this.s3Form.getProperty('action'),
					id: this.options.name + 'Swiffy',
					fieldName: 'file',
					limitSize: this.options.maxUploadSize,
					path: this.options.path,
					target: this.browse,
					debug: this.options.debug,
					onLoad: function() {
						this.loaded = true;
						this.switchToFlashUploader();
						this.fireEvent('onLoad');
					}.bind(this),
					onSelect: function(file) {
						if(file.size > this.options.maxUploadSize || file.size == 0) {
							this.fireEvent('onSelectError', file);
							return false;
						}
						else {
							var fileName = file.name.trim();
							this.text.setProperty('value', fileName);
							this.s3ContentType.value = MIMEtype.getType(fileName);
							this.fireEvent('onSelect', file);
							return true;
						}
					}.bind(this),
					fileError: this.uploadError.bind(this),
					fileUpload: function(file, options) {
						this.progress.removeClass('hidden');
						this.fireEvent('onUpload', file);
					}.bind(this),
					fileComplete: function(file, response) {
						var fileUrl = null;
						if(response == '201') {
							fileUrl = this.options.s3BucketUri + encodeURIComponent(this.options.s3FilePrefix + file.name.trim());
						}
						else {
							if(Browser.Engine.trident) {
								var xmlDoc = new ActiveXObject('Microsoft.XMLDOM');
								xmlDoc.async = false;
								xmlDoc.loadXML(response);
							} else {
								var xmlDoc = new DOMParser().parseFromString(response, 'text/xml');
							}
							var locationElements = xmlDoc.getElementsByTagName('Location');
							if(locationElements.length) {
								fileUrl = locationElements[0].childNodes[0].nodeValue;
							}
							else {
								var messageElements = xmlDoc.getElementsByTagName('Message');
								if(messageElements.length) {
									var message = messageElements[0].childNodes[0].nodeValue;
								}
								else {
									var message = '';
								}
								this.uploadError(file, message, '');
							}
						}
						if(fileUrl) {
							this.fakeFile.setProperty('value', fileUrl);
							this.fireEvent('onComplete', {file: file, response: response});
							this.form.submit();
						}
					}.bind(this)
				});
				this.browse.addEvent('click', function(event) {
					event.stop();
					this.swiffy.browse();
				}.bind(this));
			}
			else {
				this.swiffy = null;
			}
		}
		else {
			this.activated = false;
		}
	},

	delaySubmit: function(){
		if(this.activated) {
			this.form.submit();
		}
	},

	submit: function() {
		if(this.activated) {
			if(this.isFlashUploader && this.swiffy.files.length) {
				this.swiffy.upload({data: this.s3Form});
			}
			else {
				this.fireEvent('onSubmit');
				this.delaySubmit.delay(100, this);
			}
		}
	},

	switchToStandardUploader: function() {
		if(this.activated && this.isFlashUploader) {
			this.text.removeProperty('id');
			this.fakeFile.removeProperty('name');
			this.file.setProperty('id', this.fileId);
			this.file.setProperty('name', this.options.fieldName);
			this.text.addClass('hidden');
			this.browse.addClass('hidden');
			this.file.removeClass('hidden');
			this.isStandardUploader = true;
			this.isFlashUploader = false;
			this.reposition();
		}
	},

	switchToFlashUploader: function() {
		if(this.loaded && this.isStandardUploader) {
			this.file.removeProperty('id');
			this.file.removeProperty('name');
			this.text.setProperty('id', this.fileId);
			this.fakeFile.setProperty('name', this.options.fieldName);
			this.file.addClass('hidden');
			this.text.removeClass('hidden');
			this.browse.removeClass('hidden');
			this.isStandardUploader = false;
			this.isFlashUploader = true;
			this.reposition();
		}
	},

	reposition: function() {
		if(this.loaded) {
			this.swiffy.reposition();
		}
	},

	sizeToKB: function(size) {
		var unit = 'B';
		if((size / 1048576) > 1) {
			unit = 'MB';
			size /= 1048576;
		} else if((size / 1024) > 1) {
			unit = 'kB';
			size /= 1024;
		}
		return size.round(1) + ' ' + unit;
	},

	uploadError: function(file, error, info) {
		this.progress.addClass('hidden');
		this.text.setProperty('value', '');
		this.fireEvent('onError', [file, error, info]);
	},

	onSelectError: function(file) {
		if(file.size == 0) {
			var message = this.options.messageEmptyUploadSize;
		}
		else {
			var message = this.options.messageMaxUploadSize.substitute({maxUploadSize: this.maxUploadSizeKB});
		}
		alert(message);
	},

	onError: function(file, error, info) {
		this.switchToStandardUploader();
		var message = {file: file.name.trim()};
		alert(this.options.messageUploadFailed.substitute(message));
	}
})


var Validate = {

	isEmail: function(value) {
		var email = value.trim().toLowerCase();
		var emailReg = /^[a-z0-9!#_=~.+-]+@[a-z0-9\.\-]+\.[a-z]{2,4}$/;
		return emailReg.test(email);
	},

	isNotEmpty: function(value) {
		return value.trim();
	},

	isPhoneNumber: function(value) {
		var phoneNumber = value.trim().replace(new RegExp('[^0-9() -]', 'g'), '');
		return phoneNumber != '';
	},

	isUrl: function(value) {
		var url = value.trim().toLowerCase();
		var urlReg = /^(https?:\/\/)?.+\..+$/i;
		return urlReg.test(url);
	},

	isDomain: function(value) {
		var domain = value.trim().toLowerCase();
		var domainReg = /^.+\..+$/i;
		return domainReg.test(domain);
	},

	isCardNumber: function(value) {
		var creditCardNumber = value.replace(new RegExp('[^0-9]', 'g'), '');
		return creditCardNumber.length >= 13;
	}
}


function isEmail(id, message) {
	var element = $(id);
	if(element) {
		if(Validate.isEmail(element.value)) {
			element.getParent('div.row').removeClass('error');
			return true;
		}
		else {
			element.getParent('div.row').addClass('error');
			addError(id, message);
		}
	}
	return false;
}

function isNotEmpty(id, message) {
	var element = $(id);
	if(element) {
		if(Validate.isNotEmpty(element.value) && (element.getProperty('data-default') !== element.value)) {
			element.getParent('div.row').removeClass('error');
			return true;
		}
		else {
			element.getParent('div.row').addClass('error');
			addError(id, message);
		}
	}
	return false;
}

function isPhoneNumber(id, message) {
	var element = $(id);
	if(element) {
		if(Validate.isPhoneNumber(element.value)) {
			element.getParent('div.row').removeClass('error');
			return true;
		}
		else {
			element.getParent('div.row').addClass('error');
			addError(id, message);
		}
	}
	return false;
}

function isUrl(id, message) {
	var element = $(id);
	if(element) {
		if(Validate.isUrl(element.value)) {
			element.getParent('div.row').removeClass('error');
			return true;
		}
		else {
			element.getParent('div.row').addClass('error');
			addError(id, message);
		}
	}
	return false;
}

function isDomain(id, message) {
	var element = $(id);
	if(element) {
		if(Validate.isDomain(element.value)) {
			element.getParent('div.row').removeClass('error');
			return true;
		}
		else {
			element.getParent('div.row').addClass('error');
			addError(id, message);
		}
	}
	return false;
}

function isCardNumber(id, message) {
	var element = $(id);
	if(element) {
		if(Validate.isCardNumber(element.value)) {
			element.removeClass('error');
			return true;
		}
		else {
			element.addClass('error');
			addError(id, message);
		}
	}
	return false;
}

function checkSource(formId, linkId, message) {
	var link = $(linkId);
	var file = $('order-file');
	if(link && file) {
		if(Validate.isUrl(link.value) || Validate.isNotEmpty(file.value)) {
			link.getParent('div.row').removeClass('error');
			file.getParent('div.row').removeClass('error');
			return true;
		}
		else {
			link.getParent('div.row').addClass('error');
			file.getParent('div.row').addClass('error');
			addError(linkId, message);
		}
	}
	return false;
}

function checkEmail(formId, emailId, message) {
	var emailElement = $(emailId);
	if(emailElement) {
		var email = emailElement.getProperty('value').trim().toLowerCase();
		var emailReg = /^[a-z]*\:\d*$/;
		if(Validate.isEmail(email) || emailReg.test(email)) {
			emailElement.getParent('div.row').removeClass('error');
			return true;
		}
		else {
			emailElement.getParent('div.row').addClass('error');
			addError(emailId, message);
		}
	}
	return false;
}

function checkPassword(formId, passwordId, message) {
	var password = $(passwordId);
	var passwordReEnter = $('re-enter');
	if(password && passwordReEnter) {
		if(password.value.trim() == passwordReEnter.value.trim()) {
			password.getParent('div.row').removeClass('error');
			passwordReEnter.getParent('div.row').removeClass('error');
			return true;
		}
		else {
			password.getParent('div.row').addClass('error');
			passwordReEnter.getParent('div.row').addClass('error');
			addError(passwordId, message);
		}
	}
	return false
}

function setFocus(element) {
	try {
		element.focus();
	}
	catch(e) {}
}

function addError(id, message)
{
	var el = $(id);
	if(el)
	{
		errorMessages[errorMessages.length] = {'id': id, 'message': message};
		if(errorMessages.length == 1)
		{
			setFocus(el);
		}
	}
}

function showErrors(formId)
{
	var el = $(formId);
	if(el)
	{
		errorHolder = el.getElements('div.info.error div.frame');
		allErrorHolders = el.getElements('div.info div.frame');
		allErrorHolders.getParent('div.info').addClass('hidden');
		if(errorHolder[0])
		{
			errorHolder[0].innerHTML = '';
		}
		if(errorMessages.length)
		{
			if(errorHolder[0])
			{
				for(var i = 0; i < errorMessages.length; i++)
				{
					new Element('p', {'data-field': errorMessages[i]['message'], 'text': errorMessages[i]['message']}).inject(errorHolder[0]);
				}
			}
			errorHolder.getParent('div.info.error').removeClass('hidden');
		}
	}
}


fileUploadSwitcher = new Class({
	Implements : [Options, Events],
	options: {
		id: null
	},
	initialize: function(item, s3FlashUploadItem){
		this.options.id = item;
		this.itemBasicUploader = $(this.options.id + '-basic-uploader');
		this.itemFlashUploader = $(this.options.id + '-flash-uploader');
		this.itemFileElement = $(this.options.id + '-file');
		this.itemCustomFileElement = $(this.options.id + '-custom-file');
		this.itemCustomFileTextElement = $(this.options.id + '-custom-file-text');
		this.itemEmptyNotes = $(this.options.id + '-empty-notes');
		this.itemBasicNotes = $(this.options.id + '-basic-notes');
		this.itemFlashNotes = $(this.options.id + '-flash-notes');
		this.s3FlashUploadder = s3FlashUploadItem;
		if(this.itemBasicUploader && this.itemFlashUploader && this.itemFileElement && this.itemCustomFileElement && this.itemCustomFileTextElement && this.itemEmptyNotes && this.itemBasicNotes && this.itemFlashNotes && this.s3FlashUploadder)
		{
			this.itemBasicUploader.addEvent('click', function(event) {
				event.stop();
				this.switchToStandardUploader();
			}.bind(this));
			this.itemFlashUploader.addEvent('click', function(event) {
				event.stop();
				this.switchToFlashUploader();
			}.bind(this));
			this.itemCustomFileElement.addEvents({
				'mouseenter': function() {
					this.itemCustomFileElement.setStyle('cursor', 'pointer');
					if(this.itemCustomFileElement.hasClass('custom-file')) {
						this.itemCustomFileElement.addClass('custom-file-hover');
					}
				}.bind(this),
				'mouseleave': function() {
					if(this.itemCustomFileElement.hasClass('custom-file')) {
						this.itemCustomFileElement.removeClass('custom-file-hover');
					}
				}.bind(this)
			});
			this.itemEmptyNotes.addClass('hidden');
			this.itemBasicNotes.removeClass('hidden');
			this.itemFlashNotes.addClass('hidden');
			this.itemCustomFileElement.removeClass('custom-file');
		}
	},
	switchToStandardUploader: function()
	{
		this.s3FlashUploadder.switchToStandardUploader();
		this.itemFlashNotes.removeClass('hidden');
		this.itemBasicNotes.addClass('hidden');
		this.itemCustomFileElement.addClass('custom-file');
		this.s3FlashUploadder.file.addEvent('change', function() {
			var itemFile = this.s3FlashUploadder.file.getProperty('value');
			this.itemCustomFileTextElement.setProperty('value', itemFile.substring(itemFile.lastIndexOf('\\') + 1, itemFile.length));
		}.bind(this));
	},
	switchToFlashUploader: function()
	{
		this.s3FlashUploadder.switchToFlashUploader();
		this.itemBasicNotes.removeClass('hidden');
		this.itemFlashNotes.addClass('hidden');
		this.itemCustomFileElement.removeClass('custom-file');
	}
});

window.addEvent('domready', function() {
	$$('a[rel=nofollow]').set('target', '_blank');
});

function onLoadContactForm() {
	if(typeof s3FlashUploadContactForm != 'undefined')
	{
		fileUploadSwitcherContact = new fileUploadSwitcher('contact', s3FlashUploadContactForm);
	}
}

function onLoadContactUs() {
	if(typeof s3FlashUploadContactUs != 'undefined')
	{
		fileUploadSwitcherContactUs = new fileUploadSwitcher('contact-us', s3FlashUploadContactUs);
	}
}

function repositionContactPopup() {
	if(typeof s3FlashUploadContactForm != 'undefined' && s3FlashUploadContactForm) {
		s3FlashUploadContactForm.reposition();
	}
}

function initContactPopup() {
	var contactResponse = $('contact-response');
	var contactFormWrapper = $('contact-form-popup-wrapper');
	if(contactResponse && contactFormWrapper) {
		contactFormWrapper.addClass('hidden');
		$$("#header a.contact-us.open-popup").fireEvent('click');
		function onCloseModal() {
			contactResponse.addClass('hidden');
			contactFormWrapper.removeClass('hidden');
			window.removeEvent('modalhide', onCloseModal);
		}
		window.addEvent('modalhide', onCloseModal);
	}
}

function getGmtOffset() {
	var d = new Date();
	var winter = new Date(d.getFullYear(), 0, 1);
	var summer = new Date(d.getFullYear(), 6, 1);
	var winterOffset = -winter.getTimezoneOffset();
	var summerOffset = -summer.getTimezoneOffset();
	return (winterOffset < summerOffset)? winterOffset: summerOffset;
}

function setGmtOffset(elementId) {
	var gmtOffsetElement = $(elementId);
	if(gmtOffsetElement) {
		gmtOffsetElement.setProperty('value', getGmtOffset());
	}
}

function initForgotPassword() {
	var forgotButton = $('forgot-password-send');
	var forgotForm = $('login-forgot-form');
	var forgotEmailFrom = $('client-login');
	var forgotEmailTo = $('client-forgot-password-email');
	if(forgotButton && forgotForm && forgotEmailFrom && forgotEmailTo)
	{
		forgotButton.addEvent('click', function(){
			errorMessages = [];
			if(isEmail('client-login', 'Please specify a valid email address.'))
			{
				forgotEmailTo.set('value', forgotEmailFrom.get('value'));
				forgotForm.submit();
			}
			showErrors('client-login-form');
			return false;
		});
	}
	return false;
}

function initClientPopup() {
	var clientResponse = $('client-response');
	var clientForgotResponse = $('client-forgot-response');
	if(clientForgotResponse || clientResponse) {
		ModalBox.open('login-popup');
		function onCloseModal() {
			if(clientResponse)
			{
				clientResponse.addClass('hidden');
			}
			if(clientForgotResponse)
			{
				clientForgotResponse.addClass('hidden');
			}
			window.removeEvent('modalhide', onCloseModal);
		}
		window.addEvent('modalhide', onCloseModal);
	}
}

window.addEvent('domready', function() {
	initContactPopup();
	initForgotPassword();
	initClientPopup();
	setGmtOffset('contact-gmt-offset');
	setGmtOffset('contact-us-gmt-offset');
})

window.addEvent('scroll', function() {
	repositionContactPopup();
})

window.addEvent('resize', function() {
	repositionContactPopup();
})
window.addEvent('modalshow', function(){
   repositionContactPopup();
});


var s3FlashUploadContactForm = null;
function enableButtonContactFormSubmit() {
	var buttonContactFormSubmit = $('contact-form-submit');
	if(buttonContactFormSubmit) {
		buttonContactFormSubmit.removeProperty('disabled');
	}
}
function disableButtonContactFormSubmit() {
	var buttonContactFormSubmit = $('contact-form-submit');
	if(buttonContactFormSubmit) {
		buttonContactFormSubmit.setProperty('disabled', 'disabled');
	}
};
function submitContactForm() {
	if(canSubmitContactForm()) {
if(s3FlashUploadContactForm) {
	s3FlashUploadContactForm.submit();
}

		return true;
	}
	else {
		return false;
	}
};
function canSubmitContactForm() {
	errorMessages = [];
	if(typeof canSubmitContactFormCustom == 'function') {
		var result = canSubmitContactFormCustom();
	}
	else {
		var result = true;
		result &= checkEmail('contact-form', 'contact-form-email', 'Please specify a valid email address.');
	result &= isNotEmpty('contact-form-message', 'Please enter your message.');
	
	}
	showErrors('contact-form');
	try{
		s3FlashUploadContactForm.reposition();
	}
	catch(e){}
	if(result) {
		return true;
	}
	else {
		return false;
	}
};
window.addEvent('domready', function() {
	var buttonContactFormSubmit = $('contact-form-submit');
	if(buttonContactFormSubmit) {
		buttonContactFormSubmit.addEvent('click', function(event) {
			event.stop();
			disableButtonContactFormSubmit();
			if(!submitContactForm()) {
				enableButtonContactFormSubmit();
			}
		});
	}
	var formContactForm = $('contact-form');
	if(formContactForm) {
		formContactForm.addEvent('submit', function(event) {
			event.stop();
			submitContactForm();
		});
	}
});


function enableButtonClientLoginFormSubmit() {
	var buttonClientLoginFormSubmit = $('client-login-form-submit');
	if(buttonClientLoginFormSubmit) {
		buttonClientLoginFormSubmit.removeProperty('disabled');
	}
}
function disableButtonClientLoginFormSubmit() {
	var buttonClientLoginFormSubmit = $('client-login-form-submit');
	if(buttonClientLoginFormSubmit) {
		buttonClientLoginFormSubmit.setProperty('disabled', 'disabled');
	}
};
function submitClientLoginForm() {
	if(canSubmitClientLoginForm()) {
		var formClientLoginForm = $('client-login-form');
		if(formClientLoginForm) {
			formClientLoginForm.submit();
		}
		return true;
	}
	else {
		return false;
	}
};
function canSubmitClientLoginForm() {
	errorMessages = [];
	if(typeof canSubmitClientLoginFormCustom == 'function') {
		var result = canSubmitClientLoginFormCustom();
	}
	else {
		var result = true;
		result &= isEmail('client-login', 'Please specify a valid email address.');
	result &= isNotEmpty('client-password', 'Please specify your password.');
	
	}
	showErrors('client-login-form');
	try{
		s3FlashUploadClientLoginForm.reposition();
	}
	catch(e){}
	if(result) {
		return true;
	}
	else {
		return false;
	}
};
window.addEvent('domready', function() {
	var buttonClientLoginFormSubmit = $('client-login-form-submit');
	if(buttonClientLoginFormSubmit) {
		buttonClientLoginFormSubmit.addEvent('click', function(event) {
			event.stop();
			disableButtonClientLoginFormSubmit();
			if(!submitClientLoginForm()) {
				enableButtonClientLoginFormSubmit();
			}
		});
	}
	var formClientLoginForm = $('client-login-form');
	if(formClientLoginForm) {
		formClientLoginForm.addEvent('submit', function(event) {
			event.stop();
			submitClientLoginForm();
		});
	}
});


function enableButtonLoginForgotFormSubmit() {
	var buttonLoginForgotFormSubmit = $('login-forgot-form-submit');
	if(buttonLoginForgotFormSubmit) {
		buttonLoginForgotFormSubmit.removeProperty('disabled');
	}
}
function disableButtonLoginForgotFormSubmit() {
	var buttonLoginForgotFormSubmit = $('login-forgot-form-submit');
	if(buttonLoginForgotFormSubmit) {
		buttonLoginForgotFormSubmit.setProperty('disabled', 'disabled');
	}
};
function submitLoginForgotForm() {
	if(canSubmitLoginForgotForm()) {
		var formLoginForgotForm = $('login-forgot-form');
		if(formLoginForgotForm) {
			formLoginForgotForm.submit();
		}
		return true;
	}
	else {
		return false;
	}
};
function canSubmitLoginForgotForm() {
	if(typeof canSubmitLoginForgotFormCustom == 'function') {
		return canSubmitLoginForgotFormCustom();
	}
	else {
		return isNotEmpty('client-forgot-password-email', 'Please specify a valid email address.') && isEmail('client-forgot-password-email', 'Please specify a valid email address.');
	}
};
window.addEvent('domready', function() {
	var buttonLoginForgotFormSubmit = $('login-forgot-form-submit');
	if(buttonLoginForgotFormSubmit) {
		buttonLoginForgotFormSubmit.addEvent('click', function(event) {
			event.stop();
			disableButtonLoginForgotFormSubmit();
			if(!submitLoginForgotForm()) {
				enableButtonLoginForgotFormSubmit();
			}
		});
	}
	var formLoginForgotForm = $('login-forgot-form');
	if(formLoginForgotForm) {
		formLoginForgotForm.addEvent('submit', function(event) {
			event.stop();
			submitLoginForgotForm();
		});
	}
});


var s3FlashUploadOrder = null;
function enableButtonOrderSubmit() {
	var buttonOrderSubmit = $('order-submit');
	if(buttonOrderSubmit) {
		buttonOrderSubmit.removeProperty('disabled');
	}
}
function disableButtonOrderSubmit() {
	var buttonOrderSubmit = $('order-submit');
	if(buttonOrderSubmit) {
		buttonOrderSubmit.setProperty('disabled', 'disabled');
	}
};
function submitOrder() {
	if(canSubmitOrder()) {
if(s3FlashUploadOrder) {
	s3FlashUploadOrder.submit();
}

		return true;
	}
	else {
		return false;
	}
};
function canSubmitOrder() {
	errorMessages = [];
	if(typeof canSubmitOrderCustom == 'function') {
		var result = canSubmitOrderCustom();
	}
	else {
		var result = true;
		result &= checkEmail('order', 'email', 'Please specify a valid email address.');
	result &= checkSource('order', 'order-link', 'Please upload your design sources or specify a link to your file(s).');
	
	}
	showErrors('order');
	try{
		s3FlashUploadOrder.reposition();
	}
	catch(e){}
	if(result) {
		return true;
	}
	else {
		return false;
	}
};
window.addEvent('domready', function() {
	var buttonOrderSubmit = $('order-submit');
	if(buttonOrderSubmit) {
		buttonOrderSubmit.addEvent('click', function(event) {
			event.stop();
			disableButtonOrderSubmit();
			if(!submitOrder()) {
				enableButtonOrderSubmit();
			}
		});
	}
	var formOrder = $('order');
	if(formOrder) {
		formOrder.addEvent('submit', function(event) {
			event.stop();
			submitOrder();
		});
	}
});


function enableButtonClientLoginPageSubmit() {
	var buttonClientLoginPageSubmit = $('client-login-page-submit');
	if(buttonClientLoginPageSubmit) {
		buttonClientLoginPageSubmit.removeProperty('disabled');
	}
}
function disableButtonClientLoginPageSubmit() {
	var buttonClientLoginPageSubmit = $('client-login-page-submit');
	if(buttonClientLoginPageSubmit) {
		buttonClientLoginPageSubmit.setProperty('disabled', 'disabled');
	}
};
function submitClientLoginPage() {
	if(canSubmitClientLoginPage()) {
		var formClientLoginPage = $('client-login-page');
		if(formClientLoginPage) {
			formClientLoginPage.submit();
		}
		return true;
	}
	else {
		return false;
	}
};
function canSubmitClientLoginPage() {
	errorMessages = [];
	if(typeof canSubmitClientLoginPageCustom == 'function') {
		var result = canSubmitClientLoginPageCustom();
	}
	else {
		var result = true;
		result &= isEmail('login-email', 'Please specify a valid email address.');
	result &= isNotEmpty('login-password', 'Please specify your password.');
	
	}
	showErrors('client-login-page');
	try{
		s3FlashUploadClientLoginPage.reposition();
	}
	catch(e){}
	if(result) {
		return true;
	}
	else {
		return false;
	}
};
window.addEvent('domready', function() {
	var buttonClientLoginPageSubmit = $('client-login-page-submit');
	if(buttonClientLoginPageSubmit) {
		buttonClientLoginPageSubmit.addEvent('click', function(event) {
			event.stop();
			disableButtonClientLoginPageSubmit();
			if(!submitClientLoginPage()) {
				enableButtonClientLoginPageSubmit();
			}
		});
	}
	var formClientLoginPage = $('client-login-page');
	if(formClientLoginPage) {
		formClientLoginPage.addEvent('submit', function(event) {
			event.stop();
			submitClientLoginPage();
		});
	}
});


function enableButtonForgotPasswordPageSubmit() {
	var buttonForgotPasswordPageSubmit = $('forgot-password-page-submit');
	if(buttonForgotPasswordPageSubmit) {
		buttonForgotPasswordPageSubmit.removeProperty('disabled');
	}
}
function disableButtonForgotPasswordPageSubmit() {
	var buttonForgotPasswordPageSubmit = $('forgot-password-page-submit');
	if(buttonForgotPasswordPageSubmit) {
		buttonForgotPasswordPageSubmit.setProperty('disabled', 'disabled');
	}
};
function submitForgotPasswordPage() {
	if(canSubmitForgotPasswordPage()) {
		var formForgotPasswordPage = $('forgot-password-page');
		if(formForgotPasswordPage) {
			formForgotPasswordPage.submit();
		}
		return true;
	}
	else {
		return false;
	}
};
function canSubmitForgotPasswordPage() {
	errorMessages = [];
	if(typeof canSubmitForgotPasswordPageCustom == 'function') {
		var result = canSubmitForgotPasswordPageCustom();
	}
	else {
		var result = true;
		result &= isEmail('send-email', 'Please specify a valid email address.');
	
	}
	showErrors('forgot-password-page');
	try{
		s3FlashUploadForgotPasswordPage.reposition();
	}
	catch(e){}
	if(result) {
		return true;
	}
	else {
		return false;
	}
};
window.addEvent('domready', function() {
	var buttonForgotPasswordPageSubmit = $('forgot-password-page-submit');
	if(buttonForgotPasswordPageSubmit) {
		buttonForgotPasswordPageSubmit.addEvent('click', function(event) {
			event.stop();
			disableButtonForgotPasswordPageSubmit();
			if(!submitForgotPasswordPage()) {
				enableButtonForgotPasswordPageSubmit();
			}
		});
	}
	var formForgotPasswordPage = $('forgot-password-page');
	if(formForgotPasswordPage) {
		formForgotPasswordPage.addEvent('submit', function(event) {
			event.stop();
			submitForgotPasswordPage();
		});
	}
});


var s3FlashUploadReply = null;
function enableButtonReplySubmit() {
	var buttonReplySubmit = $('reply-submit');
	if(buttonReplySubmit) {
		buttonReplySubmit.removeProperty('disabled');
	}
}
function disableButtonReplySubmit() {
	var buttonReplySubmit = $('reply-submit');
	if(buttonReplySubmit) {
		buttonReplySubmit.setProperty('disabled', 'disabled');
	}
};
function submitReply() {
	if(canSubmitReply()) {
if(s3FlashUploadReply) {
	s3FlashUploadReply.submit();
}

		return true;
	}
	else {
		return false;
	}
};
function canSubmitReply() {
	errorMessages = [];
	if(typeof canSubmitReplyCustom == 'function') {
		var result = canSubmitReplyCustom();
	}
	else {
		var result = true;
		result &= isNotEmpty('notes', 'Please enter your message.');
	
	}
	showErrors('reply');
	try{
		s3FlashUploadReply.reposition();
	}
	catch(e){}
	if(result) {
		return true;
	}
	else {
		return false;
	}
};
window.addEvent('domready', function() {
	var buttonReplySubmit = $('reply-submit');
	if(buttonReplySubmit) {
		buttonReplySubmit.addEvent('click', function(event) {
			event.stop();
			disableButtonReplySubmit();
			if(!submitReply()) {
				enableButtonReplySubmit();
			}
		});
	}
	var formReply = $('reply');
	if(formReply) {
		formReply.addEvent('submit', function(event) {
			event.stop();
			submitReply();
		});
	}
});


function enableButtonAddbannerSubmit() {
	var buttonAddbannerSubmit = $('addbanner-submit');
	if(buttonAddbannerSubmit) {
		buttonAddbannerSubmit.removeProperty('disabled');
	}
}
function disableButtonAddbannerSubmit() {
	var buttonAddbannerSubmit = $('addbanner-submit');
	if(buttonAddbannerSubmit) {
		buttonAddbannerSubmit.setProperty('disabled', 'disabled');
	}
};
function submitAddbanner() {
	if(canSubmitAddbanner()) {
		var formAddbanner = $('addbanner');
		if(formAddbanner) {
			formAddbanner.submit();
		}
		return true;
	}
	else {
		return false;
	}
};
function canSubmitAddbanner() {
	if(typeof canSubmitAddbannerCustom == 'function') {
		return canSubmitAddbannerCustom();
	}
	else {
		return isNotEmpty('addbanner-notes', 'Please enter your message.');
	}
};
window.addEvent('domready', function() {
	var buttonAddbannerSubmit = $('addbanner-submit');
	if(buttonAddbannerSubmit) {
		buttonAddbannerSubmit.addEvent('click', function(event) {
			event.stop();
			disableButtonAddbannerSubmit();
			if(!submitAddbanner()) {
				enableButtonAddbannerSubmit();
			}
		});
	}
	var formAddbanner = $('addbanner');
	if(formAddbanner) {
		formAddbanner.addEvent('submit', function(event) {
			event.stop();
			submitAddbanner();
		});
	}
});


var s3FlashUploadTicket = null;
function enableButtonTicketSubmit() {
	var buttonTicketSubmit = $('ticket-submit');
	if(buttonTicketSubmit) {
		buttonTicketSubmit.removeProperty('disabled');
	}
}
function disableButtonTicketSubmit() {
	var buttonTicketSubmit = $('ticket-submit');
	if(buttonTicketSubmit) {
		buttonTicketSubmit.setProperty('disabled', 'disabled');
	}
};
function submitTicket() {
	if(canSubmitTicket()) {
if(s3FlashUploadTicket) {
	s3FlashUploadTicket.submit();
}

		return true;
	}
	else {
		return false;
	}
};
function canSubmitTicket() {
	errorMessages = [];
	if(typeof canSubmitTicketCustom == 'function') {
		var result = canSubmitTicketCustom();
	}
	else {
		var result = true;
		result &= isNotEmpty('notes', 'Please enter your message.');
	
	}
	showErrors('ticket');
	try{
		s3FlashUploadTicket.reposition();
	}
	catch(e){}
	if(result) {
		return true;
	}
	else {
		return false;
	}
};
window.addEvent('domready', function() {
	var buttonTicketSubmit = $('ticket-submit');
	if(buttonTicketSubmit) {
		buttonTicketSubmit.addEvent('click', function(event) {
			event.stop();
			disableButtonTicketSubmit();
			if(!submitTicket()) {
				enableButtonTicketSubmit();
			}
		});
	}
	var formTicket = $('ticket');
	if(formTicket) {
		formTicket.addEvent('submit', function(event) {
			event.stop();
			submitTicket();
		});
	}
});


function enableButtonProfileSubmit() {
	var buttonProfileSubmit = $('profile-submit');
	if(buttonProfileSubmit) {
		buttonProfileSubmit.removeProperty('disabled');
	}
}
function disableButtonProfileSubmit() {
	var buttonProfileSubmit = $('profile-submit');
	if(buttonProfileSubmit) {
		buttonProfileSubmit.setProperty('disabled', 'disabled');
	}
};
function submitProfile() {
	if(canSubmitProfile()) {
		var formProfile = $('profile');
		if(formProfile) {
			formProfile.submit();
		}
		return true;
	}
	else {
		return false;
	}
};
function canSubmitProfile() {
	errorMessages = [];
	if(typeof canSubmitProfileCustom == 'function') {
		var result = canSubmitProfileCustom();
	}
	else {
		var result = true;
		result &= isEmail('email', 'Please specify a valid email address.');
	result &= checkPassword('profile', 'password', 'Your passwords don\'t match. Please re-enter your password.');
	
	}
	showErrors('profile');
	try{
		s3FlashUploadProfile.reposition();
	}
	catch(e){}
	if(result) {
		return true;
	}
	else {
		return false;
	}
};
window.addEvent('domready', function() {
	var buttonProfileSubmit = $('profile-submit');
	if(buttonProfileSubmit) {
		buttonProfileSubmit.addEvent('click', function(event) {
			event.stop();
			disableButtonProfileSubmit();
			if(!submitProfile()) {
				enableButtonProfileSubmit();
			}
		});
	}
	var formProfile = $('profile');
	if(formProfile) {
		formProfile.addEvent('submit', function(event) {
			event.stop();
			submitProfile();
		});
	}
});


var s3FlashUploadContactUs = null;
function enableButtonContactUsSubmit() {
	var buttonContactUsSubmit = $('contact-us-submit');
	if(buttonContactUsSubmit) {
		buttonContactUsSubmit.removeProperty('disabled');
	}
}
function disableButtonContactUsSubmit() {
	var buttonContactUsSubmit = $('contact-us-submit');
	if(buttonContactUsSubmit) {
		buttonContactUsSubmit.setProperty('disabled', 'disabled');
	}
};
function submitContactUs() {
	if(canSubmitContactUs()) {
if(s3FlashUploadContactUs) {
	s3FlashUploadContactUs.submit();
}

		return true;
	}
	else {
		return false;
	}
};
function canSubmitContactUs() {
	errorMessages = [];
	if(typeof canSubmitContactUsCustom == 'function') {
		var result = canSubmitContactUsCustom();
	}
	else {
		var result = true;
		result &= checkEmail('contact-us', 'contact-us-email', 'Please specify a valid email address.');
	result &= isNotEmpty('contact-us-message', 'Please enter your message.');
	
	}
	showErrors('contact-us');
	try{
		s3FlashUploadContactUs.reposition();
	}
	catch(e){}
	if(result) {
		return true;
	}
	else {
		return false;
	}
};
window.addEvent('domready', function() {
	var buttonContactUsSubmit = $('contact-us-submit');
	if(buttonContactUsSubmit) {
		buttonContactUsSubmit.addEvent('click', function(event) {
			event.stop();
			disableButtonContactUsSubmit();
			if(!submitContactUs()) {
				enableButtonContactUsSubmit();
			}
		});
	}
	var formContactUs = $('contact-us');
	if(formContactUs) {
		formContactUs.addEvent('submit', function(event) {
			event.stop();
			submitContactUs();
		});
	}
});



