Event.observe(window,"load",function(){
	bindGallery();
	bindJaxCase();
	bindFlv();
	bindConfirmation();
	bindSortable();
	bindRemover();
	bindHelpers();
	bindHiddenItems();
	bindSearchTerm();
});


function bindSearchTerm() {
	if (q=$('searchterm')) {
		ph = q.getAttribute('placeholder');
		q.observe("focus",function(ev){
			q.value = (q.value==ph)? '' : q.value;
		});
		q.observe("blur",function(ev){
			q.value = (q.value=='')? ph : q.value;
		});
	}
}

/**
 * Fix gallery scroller size
 */
function bindGallery() {
	(s=$('image-slider'))? s.setStyle({width: $('image-meter').getWidth()+'px'}) : '';
}

function bindJaxCase() {
	$$(".asjax").each(function(el){
		el.onclick = function(){
			href = el.href;
			//получим расширение
			href = href.replace(/\.(html|php|htm)$/,"")+".jax";
			
			new Ajax.Request(href,{
				method: 'get',
				evalJS: 'force',
				onSuccess: function(transport){
					cuu = el.cumulativeOffset();
					activateJaxWindow(transport.responseText);
					moveJaxWindow(cuu[0]-150,cuu[1]-100);
					
					updateBasket();
				}
			});
			return false;
		};
	});
}

function updateBasket() {
	new Ajax.Request("/update_basket.jax",{
		method: 'get',
		onSuccess: function(transport){
			if (transport.responseText!='') {
				$("basket-content").innerHTML = transport.responseText;
			}
		}
	});
}

//двигаем всплывающее окно в точку (x,y) с поправкой на ширину экрана
function moveJaxWindow(x,y) {
	if (j=$("jax-window")) {
		//Если всплывающее окно выходит за границу окна браузера, сдвигаем окно к границе
		x=(x > (dt=document.viewport.getWidth()-j.getWidth()))? dt : x;
		j.setStyle({'top': y+'px','left':x+'px'});
	}
}

function moveWindow(win,x,y) {
	if (j=$(win)) {
		//Если всплывающее окно выходит за границу окна браузера, сдвигаем окно к границе
		x=(x > (dt=document.viewport.getWidth()-j.getWidth()))? dt : x;
		j.setStyle({'top': y+'px','left':x+'px'});
	}
}

function activateJaxWindow(response) {
	
	$("jax-window").innerHTML = response;
	
	
	scrollOffset = document.viewport.getScrollOffsets();
	viewHeight = document.viewport.getHeight();
	
	topOf = viewHeight/2 + scrollOffset[1] - 70;
	$("jax-window").setStyle({'top': topOf+'px'});
	
	$("jax-window").show();
	
	//alert('d');
	
	if ($("whish-reg-form")) {
		
		$("whish-reg-form").down("input[type='submit']").observe('click',function(ev){
			
			//валидация
			Event.stop(ev);
			if ($("whish-reg-form").down("input[name='mail']").value=='') {
				alert('Укажите, пожалуйста, свой адрес электронной почты');
			} else {
				$("whish-reg-form").request({
					onComplete: function(transport) {
						activateJaxWindow(transport.responseText);
						
					}
				
				});
				
			}
			
			
			
			
			
			
		});
	}
	
	
}

/**
 * Вешает обработчик событий на формы авторизации при заказе
 * Как-то это по-другому сделать надо
 */
Event.observe(window,"load",function(ev){
	if (!$("passwoedFieeld")) {
		return;
	}
	
	if ($('radioPass').checked) {
		$("passwoedFieeld").show();
	} else {
		$("passwoedFieeld").hide();
	}
	
	Event.observe('radioPass','change',function(){
		if ($('radioPass').checked) {
			$("passwoedFieeld").show();
		} else {
			$("passwoedFieeld").hide();
		}
	});
	
	Event.observe('radioNew','change',function(){
		if ($('radioNew').checked) {
			$("passwoedFieeld").hide();
		} else {
			$("passwoedFieeld").show();
		}
	});
});

function bindFlv() {
	$$("a").each(function(el){
				
		if (el.href.match(/.flv/)) {
			
			if (Prototype.Browser.IE) {
				string = '<object height="400" width="340">'+
							'<param name="movie" value="/admin/swf/flvplayer.swf"/>'+
							'<param name="allowFullScreen" value="true"/>'+
							'<param name="flashvars" value="way='+el.href+'&amp;swf=/admin/swf/flvplayer.swf&amp;w=400&amp;h=340&amp;autoplay=0&amp;tools=1&amp;skin=whiteblack&amp;volume=70&amp;comment=rolik"/>'+
							'<embed height="340" width="400" src="/admin/swf/flvplayer.swf" allowfullscreen="true" type="application/x-shockwave-flash" flashvars="way='+el.href+'&amp;swf=/admin/swf/flvplayer.swf&amp;w=400&amp;h=340&amp;autoplay=0&amp;tools=1&amp;skin=whiteblack&amp;volume=70&amp;comment=rolik" bgcolor="#FFFFFF"/>'+
						'</object>';
				el.parentNode.appendChild( new Element("div").update(string));
				el.remove();
				return;
			}
			
			object = new Element("object",{width: 340,height: 400});
			
			param1 = new Element("param",{name:'movie','value':'/admin/swf/flvplayer.swf'});
			param2 = new Element("param",{name:'allowFullScreen','value':'true'});
			
			flashvars = 'way='+el.href+
					'&amp;swf=/admin/swf/flvplayer.swf&amp;w=400&amp;h=340&amp;autoplay=0&amp;tools=1&amp;skin=whiteblack&amp;volume=70&amp;comment=rolik';
					
			param3 = new Element("param",{name:'flashvars','value':flashvars});
			embedy = new Element("embed",{
				src: "/admin/swf/flvplayer.swf",
				allowFullScreen: "true",
				type: "application/x-shockwave-flash",
				flashvars: flashvars,
				bgcolor: "#FFFFFF",
				width: "400",
				height: "340"
			});
			
			object.appendChild(param1);
			object.appendChild(param2);
			object.appendChild(param3);
			object.appendChild(embedy);
			
			el.parentNode.appendChild(object);
			el.remove();
		}
	});
	
	
}

function bindConfirmation() {
	
	if (c=$('confirmation')) {
		c.type='button';
		
		Event.observe(c,'click',function(){
			$("confirmation_form").submit();
			/*if (!$('agree') || !$('agree').checked) {
				alert('Вы должны быть согласны с правилами продажи');
				return false;
			} else {*/
			/*}*/
		});
	}
	
}


function bindSortable() {
	
	list = $$('.sortable-list')[0];
	if (list==undefined) {
		return false;
	}
	
	pab = $$('.sort-price-ask')[0];
	
	if (pab==undefined) {
		return false;
		
	}
	
	lst = new Slist(list);
	
	lst.addButton($$('.sort-price-ask')[0],"price-asc");
	lst.addButton($$('.sort-price-desk')[0],"price-desc");
	lst.addButton($$('.sort-default')[0],"default");
	
	
}

var Slist = Class.create({
	list: null,	items: [], def: [],
	
	initialize: function(list) {
		this.list = list;
		var lst = [];
		$A(this.list.childNodes).each(function(el){
			hs = new Hash();
			hs.set('item',el);
			hs.set('price',parseInt($(el).down('.price').innerHTML));
			lst[lst.length]=hs;
		});
		this.items = lst;
		this.def = lst.clone();
	},
	
	addButton: function (button,action) {
		
		switch (action) {
			case 'price-asc':
				this.bindPriceAsc(button);
			break;
			case 'price-desc':
				this.bindPriceDesc(button);
			break;
			case 'default':
				this.bindDefault(button);
			break;
		}
		return this;
		
		
	},
	
	bindPriceAsc: function(but) {
		Event.observe(but,'click',this.sortAsc.bindAsEventListener(this,but));
	},
	bindPriceDesc: function(but) {
		Event.observe(but,'click',this.sortDesc.bindAsEventListener(this,but));
	},
	bindDefault: function(but) {
		Event.observe(but,'click',this.sortDefault.bindAsEventListener(this,but));
	},
	
	sortAsc: function(ev,but) {
		this.items.sort(function(a,b){return a.get('price')-b.get('price')});
		this.flush();
		this.clearButton(but);
	},
	
	sortDesc: function(ev,but) {
		this.items.sort(function(a,b){return b.get('price')-a.get('price');});
		this.flush();
		this.clearButton(but);
	},
	
	sortDefault: function(ev,but) {
		//отсортируем 
		this.items = this.def.clone();
		this.flush();
		this.clearButton(but);
	},
	clearButton: function(but) {
		but.siblings().each(function(el){el.addClassName('pslink')});
		but.removeClassName('pslink');
	},
	
	
	flush: function() {
		$A(this.list.childNodes).each(function(el){el.remove()});
		$A(this.items).each(function(el){
			$(this.list).appendChild(el.get('item'));
		});
	}
	


});


function bindRemover() {
	
	$$(".whishlistremove").each(function(el){
		var block  = el.up('.item');
		
		el.onclick = function(){
			href = el.href;
			//получим расширение
			href = href.replace(/\.(html|php|htm)$/,"")+".jax";
			
			new Ajax.Request(href,{
				method: 'get',
				onSuccess: function(transport){
					
					if (transport.responseText!='') {
						activateJaxWindow(transport.responseText);
					}
					block.hide();
				
				}
			});
			
			
			return false;
		}
	});
}



function bindHelpers() {
	$$("ins.helpme").each(function(el){
		Event.observe(el,'click',showHelp.bindAsEventListener());
	});
}

function showHelp(ev) {
	el = ev.element("ins");
	
	if ($('help-window').visible()) {
		$('help-window').hide();
		return;
	}
	
	rel = el.getAttribute('rel');
	$('help-content').update('');
	new Ajax.Updater('help-content',"/help/get_help."+rel+".jax");
	$('help-window').show();
	
	moveWindow('help-window',ev.pointerX()-10,ev.pointerY()+15);
	
}

function bindHiddenItems() {
	$$("img[rel='hide']").each(function(im){
		im.setStyle({opacity: 0.7});
		
	});
	
	
}












