var cur_cat_elem;
var a_root_url  = window.parent.location.href.split('/');
var root_url    = a_root_url[0] + '//' + a_root_url[2] + '/';
var cur_view    = 2;
var sw_view;
var fr_src = '';
var find_result = null;
var astable_result = null;

function number_format(number, decimals, dec_point, thousands_sep){
	if ($chk(number)) {
		var exponent = "";
		var numberstr = number.toString ();
		var eindex = numberstr.indexOf ("e");
		var i, z;
		if (eindex > -1) {
			exponent = numberstr.substring (eindex);
			number = parseFloat (numberstr.substring (0, eindex));
		}
		
		if(decimals != null){
			var temp = Math.pow (10, decimals);
			number = Math.round (number * temp) / temp;
		}
		var sign = number < 0 ? "-" : "";
		var integer = (number > 0 ? Math.floor (number) : Math.abs (Math.ceil (number))).toString ();
		
		var fractional = number.toString ().substring (integer.length + sign.length);
		dec_point = dec_point != null ? dec_point : ".";
		fractional = decimals != null && decimals > 0 || fractional.length > 1 ? (dec_point + fractional.substring (1)) : "";
		if(decimals != null && decimals > 0) {
			for(i = fractional.length - 1, z = decimals; i < z; ++i)
				fractional += "0";
		}
		
		thousands_sep = (thousands_sep != dec_point || fractional.length == 0) ? 
		              thousands_sep : null;
		if(thousands_sep != null && thousands_sep != "") {
			for (i = integer.length - 3; i > 0; i -= 3)
				integer = integer.substring (0 , i) + thousands_sep + integer.substring (i);
		}
		return sign + integer + fractional + exponent;
	} else return '';	
}

function currency(value) {
	return number_format(value, 0, '.', ' ');
}

function order_p_checkParams(form) {
	if (!checkParam(form, 'Введите свое имя!', 'name'))	return false;
	
	if (!form.elements['phone'].value && !form.elements['email'].value) {
		alert('Введите свой контактный телефон, или e-mail для связи с вами!');
		if (!form.elements['phone'].value) form.elements['phone'].focus();
		else form.elements['email'].focus()
		return false;
	}
	
	var email_a = form.elements['email'].value.split('@');
	if (email_a.length == 2) {
		email_a = email_a[1].split('.');
		if (email_a.length == 2) 
			return true;
	}
	
	if (!form.elements['phone'].value) {
		alert('Неверный формат эл. почты');
		form.elements['email'].focus();
		return false;
	} else return true;	
}

function checkParam(form, msg, elemName) {
	if (!form.elements[elemName].value) {
		alert(msg);
		form.elements[elemName].focus();
	} else {
        if ((elemName == 'email') && !checkEmail(form.elements[elemName])) {
		  alert(msg);
		  form.elements[elemName].focus();
        } return true;
    }	
	return false;
}

function checkEmail(value) {
	var email_a = value.split('@');
	if (email_a.length == 2) {
		email_a = email_a[1].split('.');
		if (email_a.length == 2) return true;
	}
	return false;
}

function checkFormParams(form, fields) {
    if (!fields) {
        fields = [
            {text:'Введите свое имя!', name:'name'},
            {text:'Введите свой контактный телефон!', name:'phone'},
            {text:'Введите свой email!', name:'email'},
            {text:'Оставьте свои пожелания!', name:'description'},
            {text:'Оставьте свои комментарии!', name:'comment'}
        ]
    }
    
    for (var i in fields) {
        var item = fields[i];
        if (form.elements[item.name]) {
        	if (!checkParam(form, item.text, item.name))
                return false;
        }
    }
    return true;
}

function order_checkParams(form) {
    return checkFormParams(form, [
        {text:'Введите свое имя!', name:'name'},
        {text:'Введите свой контактный телефон!', name:'phone'},
        {text:'Оставьте свои пожелания!', name:'description'},
    ]);
	return true;	
}

function setOrderParams(frame, productin, textin, summ, article) {
	frame.form.prepare(textin);
	if (frame.form.elements['product'] && productin) 
		frame.form.elements['product'].value = productin;
	if (frame.form.elements['summ']) 
		frame.form.elements['summ'].value = summ;
	if (frame.form.elements['article'] && article) 
		frame.form.elements['article'].value = article;
}

function toggleOrder(frame, productin, textin, summ, article) {
	if (frame.parentNode.getStyle('opacity') == 0) {
		frame.tween.start({'opacity': [1]});
		setOrderParams(frame, productin, textin, summ, article);
	} else frame.tween.start({'opacity': [0]});
}

function showOrder(parent, productin, textin, summ, article) {	// Показывает форму заявки
	var ifname = 'order';
	if (productin) ifname += '_p';
	var frame = $(ifname); 
	if (!frame) {
		parent = $(parent);
		var fwidth = 316;
		var fheight = 300;
		if (productin) fheight = 415;
		
		if (parent.getCoordinates) {
			var box = parent.getCoordinates();
			box.top += box.height;
			box.left = box.left + ((box.width - fwidth) / 2).toInt();
			if (box.top + fheight > document.body.scrollTop + window.getHeight())
				box.top -= box.height + fheight + 20;
			if (box.top < 0) box.top = 0;	
			if (box.left < 0) box.left = 0;
		} else return;		
		var base_line = new Element('div', {'class':'order_container', 'styles':{ 
													'width':fwidth,
													'height':fheight,
													'left':box.left,
													'top':box.top}}).inject(document.body);
													
		var moveHandle = new Element('div', {'styles': {'position': 'absolute', 'z-index':504, 
											'width': fwidth - 30, 'height':40, 'cursor':'pointer'}}).inject(base_line);											
		frame = new Element('iframe', {'id':ifname, 'class':'order', 'frameborder':'no', 'marginheight':0, 'marginwidth':0,
                                'allowtransparency':'', 'scrolling':'no', 
                                'styles':{'width':fwidth, 'height':fheight}}).inject(base_line);

		var close_layer = new Element('div', {'styles': {'position': 'absolute', 'z-index':503, 'margin-left':285, 'margin-top':-fheight}}).inject(base_line);											
		var close_button = new Element('a', {'class': 'close', 'href': ''}).inject(close_layer);
		close_button.addEvent('click', (function(e) {
							var event = new Event(e);
							toggleOrder(frame);
							event.stop(); 
						}).bind(frame));
													
		var link = "index.php?option=com_vproduct&view=order";
		if (!productin) link += '&phone=1';											
		frame.src = link;
		frame.addEvent('load', function() {
									if (!this.slide) {
										this.tween = new Fx.Styles(this.parentNode, {duration: 200, wait: false});
										this.parentNode.setStyle('display', 'block');
										this.parentNode.setStyle('opacity', 0);
										(function() {
											new Drag.Move(this.parentNode, {'handle':moveHandle});
											toggleOrder(this, productin, textin, summ, article);
										}).delay(100, this);
									} 
								});
	} else toggleOrder(frame, productin, textin, summ, article);
}

function showCalc() {	// Показывает фильтр на странице продукции
	var smallCalc = $('smallCalc');
//	smallCalc.slide.toggle();
	if (smallCalc.getStyle('opacity') == 0)
		 smallCalc.tween.start({'opacity': [1]});
	else smallCalc.tween.start({'opacity': [0]});
}

function getIDInLink(link, paramName) {
	var a = link.split('/');
	for (var i=0;i<a.length;i++) {
		var pa = a[i].split('.');
		if ((pa[1] == 'html') && (pa[0].toInt() > 0)) return pa[0];
	}
	return 0;
}

function sendCatRequest(iframe, a_elem) {
	var cat_id = getIDInLink(a_elem.href, 'cat');
	if (cat_id) {									
		if (cur_cat_elem) cur_cat_elem.getParent().className = '';						// Если уже есть выбранная категория, тогда снимаем метку 
		a_elem.getParent().className = 'current';										// а на выбранную ставим метку
		cur_cat_elem = a_elem;
		var obstacle = $('vp_calc_obstacle');											// Получаем шторку фильтра
		if (obstacle.getStyle('display') == 'none') {									// Если она не видима
			obstacle.setStyles({'display':'block', 'opacity':0});						// Делаем видимой и прозрачной
			if (!obstacle.tween) {														// Если нет плагина Fx для шторки
				obstacle.tween = new Fx.Styles(obstacle, {duration: 600, wait: false,	// Создаем плагин плавного появления шторки
					onComplete: (function(){											// Обработчик события плагина
						if (this.getStyle('opacity') == 0) {
							this.setStyle('display', 'none');							// Если шторка изчезла, тогда делаем ее невидимой
						}
					}).bind(obstacle)});
			}	
		}
		obstacle.getElement('h3').innerHTML = a_elem.innerHTML;					// На шторку выводим название выбранной категории
		if (a_elem.getParent().getElement('div'))
            obstacle.getElement('div.description').innerHTML = a_elem.getParent().getElement('div').getText();    	// На шторку выводим описание выбранной категории
		else obstacle.getElement('div.description').innerHTML = '';
		updateFilter(cat_id, 0, 0, 0, 0, 0, 0, 0, function() {
            var obstacle = $('vp_calc_obstacle'); // Запускаем проявление шторки только после загрузки фрейма скроллинга
			if ((obstacle.getStyle('opacity') == 0) && 
				(obstacle.getStyle('display') == 'block')) 
				obstacle.tween.start({'opacity':[1]});
        });
		var obcont = obstacle.getElement('.ob-cont');
		obcont.setStyle('margin-top', ((obstacle.getCoordinates().height - obcont.getCoordinates().height) / 2).toInt());
	}
}

function catClose() {
	var obstacle = $('vp_calc_obstacle');					// Получаем шторку фильтра
	if (obstacle.getStyle('display') == 'block') {			// Если она видима
    	obstacle.tween.start({'opacity':[0]});             	// Плавно изчезает шторка текущей категории
    	sendParams(); 										// Отправлеяем запрос по текущему состоянию фильтра
    	if (cur_cat_elem) {									// Если есть выбранный пункт каталога, тогда снимаем метку с него
    		cur_cat_elem.getParent().className = '';
    		cur_cat_elem = null;
    	}
    	return true;
    }
    return false;
}

function prepareCatLinks(elems) {						// Подготавливает ссылки в меню категорий
	elems.each(function(item, index, arr) {				// Перебираем ссылки
		item.addEvent('click', (function(event) {		// Обрабатываем собитие клика на ссылке
			var e = new Event(event);
			var find_result = $('find_result');			// Получаем фрейм скроллинга
			if (find_result) {
				sendCatRequest(find_result, this);		// Обрабатываем ссылку
				e.stop();								// Останавливаем событие 
			}	
		}).bind(item));
	});
}

function createEmbed(params, parent) {
    if (window.ie || window.opera) {  // О этот IE!
        var embed = (new Element('div', {'class':'embed-container'})).inject(parent);
        if (params.styles) embed.setStyles(params.styles);
        var html_str = '<embed';
        for (var i in params)
            if ($type(params[i]) != 'object')
                html_str += ' ' + i + '="' + params[i] + '"';
        html_str += ' />';    
        embed.innerHTML += html_str;
    } else {
        var embed = (new Element('embed', params)).inject(parent);
    }
    return embed;
}

function tableRefresh() {
    if (cur_view == 1) { 
        var items = $$('.ss-item');
        var box = document.body.getCoordinates(); 
        if (items.length > 0) {
            var ibox = items[0].getCoordinates();
            var line_count = (box.width / ibox.width).toInt();
            if (line_count > items.length) line_count = items.length;
            $('full').setStyle('width', line_count * ibox.width);
        }
    }
}

function setView(num, onLoadProc)
{
    cur_view = num;
    if ($('wrapper')) Cookie.set('cur-view', cur_view); // Устанавливаем вид по умолчанию только на главной странице
    if (cur_view == 2) {
        var update_src = "option=com_vproduct&view=" + sw_view + "&" + fr_src;
        var prev_query = (new String(find_result.src)).split('?');
    	if (update_src != prev_query[1]) {
            find_result.removeEvents('load');
            if (onLoadProc) find_result.addEvent('load', onLoadProc);
            find_result.src = '?' + update_src;
        }
        find_result.setStyle('display', 'block');
        if (astable_result) astable_result.setStyle('display', 'none');
    } else if (astable_result) {
        find_result.setStyle('display', 'none');
        astable_result.setStyle('display', 'block');
        if (astable_result.src != fr_src) {
            if (!astable_result.src)
                Asset.css('components/com_vproduct/views/slideshow/tmpl/default.css');
            astable_result.addClass('loading');
            (new Ajax("?option=com_vproduct&view=astable&" + fr_src, {'method':'get', 'onComplete': 
                function(receive) {
                    astable_result.src = fr_src;
                    astable_result.innerHTML = receive;
                    tableRefresh();
                    if (onLoadProc) onLoadProc();
                    astable_result.removeClass('loading');
                    if (window.ie6) $('footer').setStyle('bottom', document.body.clientHeight); 
                }
            })).request();
        }
    }
        
    var vb = $('views-block');
    if (vb) {
        vb.getElement('.view-item' + cur_view).addClass('current' + cur_view);
        vb.getElement('.view-item' + ((cur_view % 2) + 1)).removeClass('current' + ((cur_view % 2) + 1));
    }
}

function updateFilter(cat, min_length, max_length, min_width, max_width, min_price, max_price, forms, onLoadProc) {
    if (cat) 
        fr_src = 'cat=' + cat;
    else {
    	fr_src = 'min_length=' + min_length;
    	fr_src += '&max_length=' + max_length;
    	fr_src += '&min_width=' + min_width;
    	fr_src += '&max_width=' + max_width;
    	fr_src += '&min_price=' + min_price;
    	fr_src += '&max_price=' + max_price;
    	fr_src += '&forms=' + forms;
    	var pid = getIDInLink(document.location.href, 'product_id');
    	if (pid) fr_src += '&product_id=' + pid; 
	}
	
	setView(cur_view, onLoadProc);
}

window.addEvent('domready', function() {

	var smallCalc = $('smallCalc');	
	if (smallCalc) {	// Если есть фильтр для маленького сколлинга
		smallCalc.setStyle('opacity', 0);	// Тщательно прячем его
		smallCalc.setStyle('margin-top', -500);
		smallCalc.tween =  new Fx.Styles(smallCalc, {duration: 200, wait: false,
							'onStart': (function() {
								if (this.getStyle('opacity') == 0)
									this.setStyle('margin-top', 0);
							}).bind(smallCalc), 
							'onComplete': (function() {
								if (this.getStyle('opacity') == 0)
									this.setStyle('margin-top', -500);
							}).bind(smallCalc)});
	}
	
	var cats = $$('div.vp-category'); // Получаем элементы каталога если на главной
	if (cats.length > 0) prepareCatLinks(cats[0].getElements('a.obstacle'));	// Обрабатываем ссылки меню каталога
	
	new Tips($$(".help,.help-tip"), {
		initialize:function(){
			this.fx = new Fx.Style(this.toolTip, "opacity", {duration: 500, wait: false}).set(0);
		},
		onShow: function(toolTip) {
			this.fx.start(0.9);
		},
		onHide: function(toolTip) {
			this.fx.start(0);
		},
		maxTitleChars: 40,
		showDelay: 300
	});
	
	$$('a').each(function(item) {
        if (item.href == 'http://www.artio.net/')
            item.setStyle('display', 'none');
    });
	
	find_result = $('find_result');
	astable_result = $('astable_result');

    if ($('wrapper')) {
        if (Cookie.get('cur-view'))
            cur_view = Cookie.get('cur-view'); // Вид по умолчанию только на главной
        else cur_view = 1;
        window.addEvent('resize', function(e) {
            tableRefresh();
        });
    }
    
    if (!window.ie6) {
        var top_anchor = $('top-anchor');
        if (top_anchor) {
            Fx.BodyScroll = Fx.Base.extend({
            	initialize: function(options) {
            		this.parent(options);
            	},
                increase:  function(){
            		window.scrollTo(0, this.now.toInt());
            	}
            })
            
            var bodyFX = new Fx.BodyScroll();
            top_anchor.toTop = function(e) {
                bodyFX.start(window.getSize().scroll.y, 0);
            }
            
            var slide = new Fx.Slide(top_anchor, {mode:'vertical'});
            slide.inOut = function(_in) {
                if (this.is_show != _in) {
                    this.is_show = _in;
                    if (_in) this.slideIn();
                    else this.slideOut();
                }
            }

            var mtl_box = document.body.getElement('.moduletableleft').getCoordinates();
            top_anchor.setStyle('display', 'block');
            slide.is_show = window.getSize().scroll.y > mtl_box.bottom;
            if (!slide.is_show) slide.hide();
            
            window.addEvent('scroll', function(e) {
                slide.inOut(window.getSize().scroll.y > mtl_box.bottom);
            });
        }
    }
});
