var scroller = new Fx.Scroll(window);

var Site = {
	
	start: function(){

		Site.setUpScrollAnchors();
		Site.liftmeup();
		//if($('cartopener')) Site.MobileCart($('cartopener'));
		new SmoothScroll();
		//ReMooz.initialize();
		$$('a.boxed img').each(function(img, i) {
			new ReMooz(img, {
				url: img.getParent().href,
				resizeOptions: {
					transition: Fx.Transitions.Back.easeOut,
					resizeLimit: {x: 600, y: 520},
					resizeOpacity: 0.4,
					hideSource: true
				}
			});
		});
		
		/* let's customize Remooz titles and alt display */
		ReMooz.prototype.options.generateTitle= function() {
			var title = this.options.title || this.element.getProperty('title');
			var text = this.options.alt || this.element.getProperty('alt');
			if (!title && !text) return false;
			//title = title.split(' :: ');
			if (title) 
				var ret = [new Element('h4').setHTML(title)];
			if(ret)
				 ret.push(new Element('p').setHTML(text));
			else 
				var ret = [new Element('p').setHTML(title)];
			return ret;
		}
		var accordion = new Accordion('h3.atStart', 'div.atStart', {
			opacity: false,
			onActive: function(toggler, element){
				$$('h3.atStart').addEvent('click', function() { 
					Site.scrollTo('contentinner');
				});
				toggler.setStyle('color', '#E16E21');
				toggler.setStyle('cursor', 'default');
				toggler.setStyle('background-image', 'url(/tpl/carbon/img/toggler_arrow_down.png)');
			},
			onBackground: function(toggler, element){
				toggler.setStyle('background-image', 'url(/tpl/carbon/img/toggler_arrow_right.png)');
				toggler.setStyle('color', '#939393');
				toggler.setStyle('cursor', 's-resize');
			}
		}, $('accordion'));
	},
	
	initMenu : function() {
		var menuitems = $$("#nav li");
		var slidefxs = [];
		//var colorfxs = [];
		
		menuitems.each(function(el, i){
			el.setStyle('opacity', '0');
			timer += 250;
			slidefxs[i] = new Fx.Style(el, 'opacity', {
				duration: 500,
				transition: Fx.Transitions.backOut,
				wait: false,
				onComplete: Site.createOver.pass([el, i])
			});
			slidefxs[i].start.delay(timer, slidefxs[i], 1);

		}, this);
	},

	MobileCart:function(cartopener) {
		console.log(cartopener);
		// let's get div position 
		var minicart=$('minicart');
		minicart.setStyle('opacity', '0');
		var uri=cartopener.getElement('a').href;
		if (uri.toString().search("=")>0)  
			var ajaxuri=uri+'&ajax=true';
		else
			var ajaxuri=uri+'?ajax=true';

		var cartfx = new Fx.Styles(minicart, {
			duration:750
			});

		cartopener.addEvent('click', function(e) { 
			e= new Event(e).stop();
			new Ajax(ajaxuri, {
				method: 'get',
				update: 'minicart',
				evalScripts: true,
				onComplete: function() {
					cartfx.start({
						'display' : 'block',
						'height' : 'auto',
						'opacity' : 1
					});
				}
			}).request();
		});
	},

	loadUrl : function(uri) {
		// let's first fade content //
	},

	createOver: function(el, i){
		var first = el.getFirst();
		var overfxs = new Fx.Styles(first, {'duration': 200, 'wait': false});
		var tocolor = 'ffffff';
		var fromcolor = '334664';
		el.addEvent('mouseover', function(){
			overfxs.start({
				'color': tocolor,
				'padding-right': 15
			});
		});
		el.addEvent('mouseout', function(){
			overfxs.start({
				'color': fromcolor,
				'padding-right': 5
			});
		});
	},

	setUpScrollAnchors: function(){
		$$('a.scroollers').each(function(lnk) {
			if(lnk.href.test("#")) {
				lnk.addEvent('click', function(){
					this.scrollTo(lnk.href.split('#')[1]);
				}.bind(this));
			}
		}, this);
	},

	scrollTo: function(element){
		if(this.scrollingTo != element) {
			this.scrollTries = 0;
			this.scrollingTo = element;
		} else this.scrollTries++;
		$clear(this.scrollTimer);
		if($(element)) scroller.toElement($(element));
		else
			if(this.scrollTries < 15) this.scrollTimer = this.scrollTo.pass(element, this).delay(100);
	},
	
	liftmeup : function() {

		var ScrollToTop = new Fx.Scroll(window);
		$$('a.totop').addEvent('click', function() { 
				ScrollToTop.toTop();
			});
		$$('a.skipcontent').addEvent('click', function() { 
				ScrollToTop.toElement('content');
			});
	
	}
}



//window.addEvent('load', Site.start);
window.addEvent('domready', function() {
	Site.start();
});


sfHover = function() {
	var sfEls = document.getElementById("nav").getElementsByTagName("LI");
	for (var i=0; i<sfEls.length; i++) {
		sfEls[i].onmouseover=function() {
			this.className+=" sfhover";
		}
		sfEls[i].onmouseout=function() {
			this.className=this.className.replace(new RegExp(" sfhover\\b"), "");
		}
	}
}
if (window.attachEvent) window.attachEvent("onload", sfHover);


var ReMooz = new Class({

	Implements: [Events, Options],

	options: {
		id: null,
		url: null,
		positionToCenter: false,
		marginBox: 10,
		resize: true,
		resizeFactor: 0.8,
		resizeLimit: false, // {x: 640, y: 640}
		hideSource: true,
		zIndex: 41,
		zIndexFocus: 42,
		addClick: true,
		resizeOptions: {},
		resizeOpacity: 1,
		fxsOptions: {},
		generateTitle: null,
		showTitle: null,
		onLoad: $empty,
		onOpen: $empty,
		onBeforeClose: $empty,
		onClose: $empty
	},

	initialize: function(element, options) {
		this.element = $(element);
		this.setOptions(options);
		this.url = this.options.url || this.element.href || this.element.src;

		this.addEvent('onBlur', function() {
			this.focussed = false;
			this.box.removeClass('remo-box-focus').setStyle('z-index', this.options.zIndex);
		}.bind(this));
		this.addEvent('onFocus', function() {
			this.focussed = true;
			this.box.addClass('remo-box-focus').setStyle('z-index', this.options.zIndexFocus);
		}.bind(this));

		this.element.addClass('remo-zoom-in').addEvent('trash', this.destroy.bind(this));

		this.clickEvent = function(e) {
			this.open.delay(1, this);
			return false;
		}.bind(this);
		if (this.options.addClick) this.bindToElement();
	},

	destroy: function(unload) {
		if (this.box && !unload) this.box.destroy();
		this.box = this.boxFx = this.image = null;
		return null;
	},

	bindToElement: function(el) {
		($(el) || this.element).addEvent('click', this.clickEvent);
		return this;
	},

	getSourceCoordinates: function() {
		var coords = this.element.getCoordinates();
		delete coords.right;
		delete coords.bottom;
		return coords;
	},

	open: function(e) {
		if (this.opened) return (e) ? this.close() : this;
		this.opened = true;
		if (!this.box) this.build();
		this.coords = this.getSourceCoordinates();
		this.boxFx.set(this.coords).start({'opacity': 0.7});
		this.box.setStyle('display', '').addClass('remo-loading');
		this.boxDrag = this.boxDrag || new Drag.Move(this.box, { // inits here because of safari
			'snap': 15,
			'onStart': function() {
				if (!this.focussed && !this.loading) {
					ReMooz.focus(this);
					this.focusEvent = true;
				}
			}.bind(this),
			'onSnap': function() {
				this.dragging = true;
				this.box.addClass('remo-box-dragging');
			}.bind(this),
			'onComplete': function() {
				if (!this.dragging && !this.focusEvent) this.close();
				this.dragging = this.focusEvent = false;
				this.box.removeClass('remo-box-dragging');
			}.bind(this)
		}).detach();
		this.fireEvent('onLoad');
		this.loadImage();
		return this;
	},

	close: function() {
		if (!this.opened) return this;
		this.fireEvent('onBeforeClose');
		this.opened = this.zoomed = false;
		ReMooz.close(this);
		if (this.loading) {
			this.box.setStyle('display', 'none');
			return this;
		}
		this.boxDrag.detach();
		this.fxs.set(this.fxs.hide);
		if (this.boxFx.timer) this.boxFx.clearChain();
		var vars = this.getSourceCoordinates();
		if (this.options.resizeOpacity != 1) vars.opacity = this.options.resizeOpacity;
		this.boxFx.start(vars).chain(function() {
			this.element.setStyle('visibility', 'visible');
			this.box.setStyle('display', 'none');
			this.fireEvent('onClose');
		}.bind(this));
		return this;
	},

	loadImage: function() {
		this.loading = true;
		var loader = new Image();
		loader.onload = loader.onabort = loader.onerror = function(fast) {
			this.loading = loader.onload = loader.onabort = loader.onerror = null;
			if (!loader.width || !this.opened) {
				this.close();
				return;
			}
			var to = {x: loader.width, y: loader.height};
			if (!this.image)
			{
				 this.image = (Client.Engine.webkit419) ? new Element('img', {'src': loader.src}) : $(loader);
				 this.image.addClass('remo-img').injectTop(this.box);
			} else loader = null;
			this.openImage.create({
				'delay': (loader && fast !== true) ? 1 : null,
				'arguments': [to],
				'bind': this
			})();
		}.bind(this);
		loader.src = this.url;
		if (loader && loader.complete && loader.onload) loader.onload(true);
	},

	openImage: function(size) {
		if (this.options.hideSource) this.element.setStyle('visibility', 'hidden');
		this[(this.options.resize) ? 'zoomRelativeTo' : 'zoomTo'](size);
	},

	zoomRelativeTo: function(to) {
		var max = this.options.resizeLimit || {
			'x': Client.getWidth() * this.options.resizeFactor,
			'y': Client.getHeight() * this.options.resizeFactor
		};
		for (var i = 2; i--;) {
			if (to.x > max.x) {
				to.y *= max.x / to.x;
				to.x = max.x;
			} else if (to.y > max.y) {
				to.x *= max.y / to.y;
				to.y = max.y;
			}
		}
		return this.zoomTo({'x': to.x.toInt(), 'y': to.y.toInt()});
	},

	zoomTo: function(to) {
		var box = window.getSize();
		var pos = (!this.options.positionToCenter) ? {
			'x': (this.coords.left + (this.coords.width / 2) - to.x / 2).toInt()
				.limit(box.scroll.x + this.options.marginBox, box.scroll.x + box.size.x - this.options.marginBox - to.x),
			'y': (this.coords.top + (this.coords.height / 2) - to.y / 2).toInt()
				.limit(box.scroll.y + this.options.marginBox, box.scroll.y + box.size.y - this.options.marginBox - to.y)
		} :  {
			'x': box.scroll.x + ((box.size.x - to.x) / 2).toInt(),
			'y': box.scroll.y + ((box.size.y - to.y) / 2).toInt()
		};
		this.box.removeClass('remo-loading');
		this.fireEvent('onOpen');
		var vars = {'left': pos.x, 'top': pos.y, 'width': to.x, 'height': to.y};
		if (this.options.resizeOpacity != 1) vars.opacity = [this.options.resizeOpacity, 1];
		else this.box.setStyle('opacity', 1);
		this.boxFx.start(vars).chain(this.openComplete.bind(this));
	},

	openComplete: function() {
		ReMooz.open(this);
		this.zoomed = true;
		this.boxDrag.attach();
		this.fxs.start($merge(this.fxs.show, (this.title) ? (this.options.showTitle || this.showTitle).call(this) : {}));
	},

	generateTitle: function() {
		var title = this.options.title || this.element.getProperty('title');
		var text = this.options.alt || this.element.getProperty('alt');
		if (!title && !text) return false;
		//title = title.split(' :: ');
		var ret = [new Element('h4').setHTML(title)];
		if (text) ret.push(new Element('p').setHTML(text));
		return ret;
	},

	showTitle: function() {
		return {1: {marginLeft: [-this.titleBox.scrollWidth, 0]}};
	},

	build: function() {
		this.box = new Element('div', {
			'class': 'remo-box',
			styles: {
				display: 'none',
				zIndex: this.options.zIndex
			},
			events: {
				click: function() {
					if (this.zoomed) return true;
					this.close();
					return false;
				}.bind(this)
			}
		});
		this.boxFx = new Fx.Styles(this.box, $merge({
			duration: 500,
			unit: 'px',
			transition: Fx.Transitions.Quart.easeOut,
			wait: false
		}, this.options.resizeOptions));

		this.btnClose = new Element('a', {
			'class': 'remo-btn-close',
			events: {'click': this.close.bind(this)}
		}).inject(this.box);
		this.fxs = new Fx.Elements(this.btnClose, $merge({
			duration: 500,
			unit: 'px',
			transition: Fx.Transitions.Quart.easeOut,
			wait: false
		}, this.options.fxsOptions));
		this.fxs.hide = {0: {opacity: 0}};
		this.fxs.show = {0: {opacity: 1}};


		this.title = (this.options.generateTitle || this.generateTitle).call(this);
		if (this.title) {
			this.titleBox = new Element('div', {
				'class': 'remo-title'
			}).inject(new Element('div', {
				'class': 'remo-title-wrap'
			}).inject(this.box));
			new Element('div', {'class': 'remo-title-bg'}).setOpacity(0.8).inject(this.titleBox);
			this.titleTxt = new Element('div', {'class': 'remo-title-txt'})
				[$type(this.title) == 'string' ? 'setHTML' : 'adopt'](this.title).inject(this.titleBox);
			this.fxs.elements.push(this.titleBox);
			this.fxs.hide[1] = {opacity: 0};
			this.fxs.show[1] = {opacity: 1};
		}
		this.fxs.set(this.fxs.hide);
		this.box.inject(document.body);
	}

});

ReMooz.factory = $extend;

ReMooz.factory({

	options: {
		zIndex: 41,
		zIndexFocus: 42,
		scanQuery: 'a.remooz',
		optionsField: 'rel'
	},

	initialize: function(elements, options) {
		options = options || {};
		$$(elements || this.options.scanQuery).each(function(el) {
			var add = el.getProperty(this.options.optionsField);
			if (add) add = Json.decode(add, true);
			el.$attributes.remooz = new ReMooz(el, add ? $merge(add, options) : options);
		}, this);
	},

	opened: [],

	open: function(obj) {
		this.focus(obj);
	},

	close: function(obj) {
		var last = this.opened.length - 1;
		if (this.opened.indexOf(obj) == last) this.focus(this.opened[last - 1]);
		this.opened.remove(obj);
	},

	focus: function(obj) {
		var last = this.opened.getLast();
		if (!obj || last == obj) return;
		if (last) last.fireEvent('onBlur', [last], 10);
		obj.fireEvent('onFocus', [obj], 10);
		this.opened.remove(obj).push(obj);
	}

});

function WRD_GetStates(SltCountry) {
	var getcountry=SltCountry.options[SltCountry.selectedIndex].value;
	if(getcountry!=0 && state[getcountry]) {
		for(i=0;SltCountry.form.state.length;i++) {
			SltCountry.form.state.options[0]=null;
		}
		for(i=0;i<=state[getcountry].length-1;i++) {
			newOption = new Option(state[getcountry][i],stateind[getcountry][i]);
			SltCountry.form.state.options[i]=newOption;
		}
		SltCountry.form.state.disabled=false;
	}
	else {
		newOption = new Option('--------------------------------','0');
		SltCountry.form.state.options[0]=newOption;
		SltCountry.form.state.disabled=true;
	}
}

