/* common function */
function toggleBlock(id, link, animate){
	var res = 1;
	if($('#'+id).css('display') == 'none'){
		if(animate)
			$('#'+id).animate({'height': 'show'}, 200);
		else
			$('#'+id).show();
	}else{
		if(animate)
			$('#'+id).animate({'height': 'hide'}, 200);
		else
			$('#'+id).hide();
	}
	if(link)
		link.blur();
}

function toggleBlock2(id, link, animate, t_class, animate_param, opened_text, closed_text){
	if(!animate_param){
		animate_param = 'height';
	}
	
	var el = typeof(id) == 'object' ? id : $('#' + id);
	
	var res = 1;
	if(t_class){
		$(link).parent().parent().toggleClass(t_class);
	}
	if($(el).css('display') == 'none'){

		if(animate){
			if(animate_param == 'height')
				$(el).animate({'height': 'show'}, 'fast');
			else
				$(el).animate({'width': 'show'}, 'fast');
		}else
			$(el).show();
		
		if(opened_text && link){
			link.innerHTML = opened_text;
		}
			
	}else{
		if(animate){
			if(animate_param == 'height')
				$(el).animate({'height': 'hide'}, 'fast');
			else
				$(el).animate({'width': 'hide'}, 'fast');
		}else
			$(el).hide();
			
		if(closed_text && link){
			link.innerHTML = closed_text;
		}
	}
	if(link)
		link.blur();
	return false;
}

/* popups */
function showPopup(id, link){
	hideAllPopups();
	if(link)
		link.blur();
	showSandBox();
	var t = ($(window).width()-$('#' + id).width())/2;
	$('#' + id).animate({height: 'show'}, 200);
	$('#' + id).css({'left': t});
	$(document).scrollTop(0);
}

function hidePopup(id){
	hideSandBox();
	var t = document.getElementById(id);
	if(t){
		t.style.display = 'none';
	}
}

function hideAllPopups(){
	$('div.login_popup').hide();
}

function showSandBox(){
	var s = document.getElementById('sandbox');
	if(!s){
		s = document.createElement('div');
		s.setAttribute('id', 'sandbox');
		document.body.appendChild(s);
	}
	s.style.height = $(document).height()-36;
	$(s).show();
}

function hideSandBox(){
	var s = document.getElementById('sandbox');
	if(s){
		s.style.display = 'none';
	}
}
			
/* init images actions */
$(document).ready(
	function(){
		/* thumb events */
		var t = $('#thumbs > a');
		if(t.length){
			$(t[0]).children().addClass('active');
			$(t).click(
				function(){
					changeCatalogPhoto(this.href, this.rel, $(this).children());
					return false;
				}
			);
		}
		/* opeing lightbox by clicking on middle size picture */
		$('#big_photo > a').click(
			function(){
				tb_show('', this.href, '');
				return false;
			}
		);
	}
);

function showFirstPhoto(){
	var t = $('#thumbs > a');
	if(t.length)
		$(t[0]).click();
}

function changeCatalogPhoto(src, src2, thumb){
	$('#big_photo > a > img').attr('src', src);
	$('#big_photo > a').attr('href', src2);
	$('#thumbs > a > img.active').removeClass('active');
	if(thumb){
		$(thumb).addClass('active');
	}
}

/* login */
function doLogin(link){
	link.blur();
	var email = document.forms['login_form'].elements['login'];
	var password = document.forms['login_form'].elements['password'];
	var remember = document.forms['login_form'].elements['remember'];
	var ok = simpleFormCheck('login_form');
	if(ok){
		var s_data = {'login': email.value, 'password': password.value}
		if(remember.checked){
			s_data.remember=1;
		}
		$.post('/login/', s_data, onLoginDone);
	}
}

function onLoginDone(text){
	if(text != ''){
		document.getElementById('login_errors').innerHTML = text;
	}else{
		window.location.reload();
	}
}

function clearLoginForm(){
	var form_name = 'login_form';
	document.getElementById('login_errors').innerHTML = '';
	for(var i=0; i<document.forms[form_name].elements.length; i++){
		if(document.forms[form_name].elements[i].className != 'button' && document.forms[form_name].elements[i].className != 'chb'){
			document.forms[form_name].elements[i].value = '';
			$(document.forms[form_name].elements[i]).removeClass('error');
		}
	}
}

/* registration */
function doRegister(link){
	if(link)
		link.blur();
	var email = document.forms['registration_form'].elements['login'];
	var password = document.forms['registration_form'].elements['password'];
	var password_r = document.forms['registration_form'].elements['password_repeat'];
	var cpt = document.forms['registration_form'].elements['captcha_word'];
	var ok = simpleFormCheck('registration_form');
	if(ok){
		$.post('/registration/', {'_save': 1, 'login': email.value, 'password': password.value, 'password_repeat': password_r.value, 'captcha_word': cpt.value}, onRegisterDone);
	}
}

function onRegisterDone(text){
	if(text != ''){
		document.getElementById('registration_errors').innerHTML = text;
	}else{
		window.location.reload();
	}
}

/* common form functions */
function onFieldFocus(el){
	$(el).removeClass('error');
}

function simpleFormCheck(form_name){
	var isok = true;
	for(var i=0; i<document.forms[form_name].elements.length; i++){
		if(document.forms[form_name].elements[i].value == ''){
			document.forms[form_name].elements[i].className = document.forms[form_name].elements[i].className == '' ? 'error' : document.forms[form_name].elements[i].className + ' error';
			isok = false;
		}
	}
	return isok;
}

/* WISHLIST */
var item_variant = 0;

function addToWishlist(id, link){
	if(link)
		link.blur();
	$.get('/wishlist/', {'action': 'add_item', 'id': id, 'item_variant': item_variant}, function(response){onAfterAddedToWishlist(response, link);});
}

function onAfterAddedToWishlist(response, link){
	if(response){
		if(link){
			link.setAttribute('href','/wishlist/');
			link.removeAttribute('onclick');
			link.innerHTML = 'в списке';
			$(link).addClass('inlist');
		}else{
			alert('Товары добавлены в список покупок');
		}
		setWishlistInfo(response);
	}else{
		showPopup('registration_form');
	}
}

function setWishlistInfo(xml, in_list){
	var count = $('count', xml).text();
	var sum = $('totalSum', xml).text();
	var cnt = $('countNum', xml).text();
	var currency = $('currency', xml).text();
	var ci = document.getElementById('cart_info');
	if(ci){
		if(cnt)
			ci.innerHTML = '<a href="/wishlist/">' + count + '</a> на сумму <strong>' + sum + ' <span class="rub">' + currency + '</span></strong>';
		else
			ci.innerHTML = 'Список покупок пуст';
			
		if(in_list){
			/* change total sum */
			if(!cnt){
				$('#wishlist_order_form').remove();
			}else{
				$('#totalSum').html(sum);
			}
		}
	}
}

function deleteWishlistItem(wishlist, item, variant, link){
	if(confirm('Вы уверены?')){
		$('#wl_item'+item).addClass('loading');
		$.get('/wishlist/', {'action': 'delete_item', 'item': item, 'item_variant': variant, 'wishlist': wishlist}, function(response){onAfterItemDeleted(response, item, variant);});
	}
	link.blur();
}

function onAfterItemDeleted(response, id, variant){	
	$('#wl_item'+id+'_'+variant).remove();
	setWishlistInfo(response, true);
}

function onWLCreateSubmit(form){
	if(form.elements['name'].value.replace(' ','') == ''){
		alert('Введите название списка');
		return false;
	}
	return true;
}

var curMoveItem = 0;
var curMoveVariant = 0;

function showMoveItemPopup(id, variant, link, ev){
	if(link)
		link.blur();
	var e = (window.event) ? window.event : ev;
	if($('div#moveitem_popup').css('display') == 'none' || curMoveItem != id){
		$('div#moveitem_popup').css('display', 'block');
		var l = e.clientX;
		var t = e.clientY + $(document).scrollTop();
		$('div#moveitem_popup').css('right', '150px');
		$('div#moveitem_popup').css('top', t);
	}else{
		if(curMoveItem == id)
			$('div#moveitem_popup').css('display', 'none');
	}
	curMoveItem = id;	
	curMoveVariant = variant;	
}

function closeMoveItemPopup(){
	$('div#moveitem_popup').css('display', 'none');
}

function moveItemToList(from_list, to_list){
	if(curMoveItem){
		$('#wl_item'+curMoveItem).addClass('loading');
		closeMoveItemPopup();
		$.get('/wishlist/', {'action': 'move_item', 'id': curMoveItem, 'item_variant': curMoveVariant, 'from': from_list, 'to': to_list}, function(response){onAfterItemMoved(response, curMoveItem, curMoveVariant);});
	}
}

function onAfterItemMoved(response, item, variant){
	$('#wl_item'+item+'_'+variant).remove();
	setWishlistInfo(response, true);
}

function changeDefaultList(sel){
	$.get('/wishlist/', {'action': 'set_default_list', 'id': sel.value}, onAfterListChanged);
}

function onAfterListChanged(response){
	window.location.reload();
}

function showConfigElements(el, link){
	
	$('#'+el).toggle('fast',
		function(){
			var t = $(link).parent();
			var p = t[0];
			if(document.getElementById(el).style.display == 'none'){
				$(p).removeClass('opened');
				$(p).addClass('closed');
			}else{
				$(p).removeClass('closed');
				$(p).addClass('opened');
			}
		}
	);
	link.blur();	
	
}

/* menu functions */
function menuItemHover(el){
	
	var steps = getMenuHoverSteps(el);
	var t = null;
	var cur_el = el;
	$(cur_el).addClass('hover');
	
	for(var i=0; i<steps[0]; i++){		
		cur_el = $(cur_el).prev();
		$(cur_el).addClass('hover');
	}
	
	var cur_el = el;
	for(var i=0; i<steps[1]; i++){		
		cur_el = $(cur_el).next();
		$(cur_el).addClass('hover');
	}
	if(this.className != 'active')
		$(this).addClass('hover');
	
}

function menuItemOut(el){

	var steps = getMenuHoverSteps(el);
	var t = null;
	var cur_el = el;
	$(cur_el).removeClass('hover');
	
	for(var i=0; i<steps[0]; i++){		
		cur_el = $(cur_el).prev();
		$(cur_el).removeClass('hover');
	}
	
	var cur_el = el;
	for(var i=0; i<steps[1]; i++){		
		cur_el = $(cur_el).next();
		$(cur_el).removeClass('hover');
	}
	$(this).removeClass('hover');
	
}

function getMenuHoverSteps(el){
	var next = 0;
	var prev = 0;
	if(el.className.indexOf('sp_l') != -1){
		next = 2;
	}else{
		if(el.className.indexOf('sp_r') != -1){
			prev = 2;
		}else{
			prev = next = 1;
		}
	}
	return new Array(prev,next);
}

function stretchMenu(cnt_id){
	
	var container = document.getElementById(cnt_id);
	var e_width = 0;
	var items = $('table > tbody > tr >td', container);
	var t;
	var items_num = 0;
	
	/* calculate width */
	for(var i=0; i<items.length; i++){
		t = $('a', items[i]);
		e_width += t[0].offsetWidth;
		items_num++;
	}
	
	if(items_num){
		var padding = (container.offsetWidth-e_width-5)/(items_num*2);
		$('table > tbody > tr >td div', container).css('padding', '0 '+padding+'px');
	}
	
	
}

/* init hor menu */
$(document).ready(
	function(){
		/*
		stretchMenu('hor_menu');
		var t = $('table.hor_menu > tbody > tr > td');
		$(t).mouseover(menuItemHover);
		$(t).mouseout(menuItemOut);
		*/
	}
);

var menu_types = new Array('catalog_sections', 'brand_list');//, 'lib_links');
function showMenu(bid, lnk){
	bid = '#' + bid;
	if($(bid).css('display') != 'block'){
		/* hide opened */
		for(var i = 0; i < menu_types.length; i++)
			if(bid != '#' + menu_types[i] && $('#' + menu_types[i]).css('display') == 'block'){
				var tt = $('div.menu_section_name.opened');
				var cur_opened = false;
				if(tt.length && tt[0].className != 'menu_section_name opened stat')
					cur_opened = tt[0];
				$('#' + menu_types[i]).animate({height: "hide"}, 300, 
					function(){
						if(cur_opened)
							$(cur_opened).removeClass('opened');
					}
				);
				//$('#' + menu_types[i]).hide();
			}
		$(bid).animate({height: "show"}, 300);
		if(lnk)
			$(lnk).addClass('opened');
	}else{
		$(bid).animate({height: "hide"}, 300, function(){if(lnk) $(lnk).removeClass('opened')});
	}
}

/* top banner functions */
var curBan = 1;

function changeBan(dir){
	var cur = document.getElementById('top_ban'+curBan);
	if(cur){
		if(dir == 0)
			curBan--;
		else
			curBan++;
		var toshow = document.getElementById('top_ban'+curBan);
		if(toshow){
			cur.style.display = 'none';
			toshow.style.display = 'block';
		}else{
			if(dir == 0)
				curBan++;
			else
				curBan--;
		}
	}
	checkControls();
}

function checkControls(){
	var t = curBan+1;
	var next = document.getElementById('ban_control_next');
	var prev = document.getElementById('ban_control_prev');
	if(document.getElementById('top_ban'+t))
		next.style.visibility = 'visible';
	else
		next.style.visibility = 'hidden';
	t = curBan-1;
	if(document.getElementById('top_ban'+t))
		prev.style.visibility = 'visible';
	else
		prev.style.visibility = 'hidden';		
}

/* init top news behavior */
$(document).ready(
	function(){
		$('div#top_news > a.news_entry').mouseover(topNewsOver);
	}
);

function topNewsOver(){
	$('div#top_news > a.news_entry.n_opened').removeClass('n_opened');
	$(this).addClass('n_opened');
}

/* news line functions */
function showNextNews(dir, auto){
	
	if(!auto){
		clearInterval(news_switcher);
		news_switcher = setInterval(function(){showNextNews(1, true)}, 3000);
	}
	
	var cur = $('#cur_news');
	$(cur).removeAttr('id');
	$(cur).hide();
	var new_el = dir == 1 ? $(cur).next() : $(cur).prev();
	if(!new_el.length){
		/* get first or last */
		var t = $('#news_line_items > div');
		new_el = dir == 1 ? t[0] : t[t.length-1];
	}
	$(new_el).fadeIn('slow');
	$(new_el).attr('id', 'cur_news');
	
}

var news_switcher = null;

$(document).ready(
	function(){
		if($('#cur_news')){
			news_switcher = setInterval(function(){showNextNews(1, true)}, 3000);
		}
	}
);

/* product details */
$(document).ready(
	function(){
		$('table#product_menu > tbody > tr > td > div > a').click(
			function(){
				showProductInfo(this.href, this);
				return false;
			}
		);
	}
);

function showProductInfo(url, it){
	$(it).parent().parent().siblings('.active').removeClass('active');
	$(it).parent().parent().addClass('active');
	$(it).blur();
	ajaxLoadContent(url, 'product_detail_info');
}

function ajaxLoadContent(url, content_id, params){
	$('#' + content_id).html('<div class="ajax_loader"><img src="/img/ajax-loader.gif"/></div>');
	$.get(url, params, 
		function(response){
			onAjaxContentLoaded(response, content_id);
		}
	);
}

function onAjaxContentLoaded(text, content_id){
	$('#' + content_id).html(text);
}


/* some catalog functions */
function expandCatalog(fid, lnk){
	lnk.blur();
	$(lnk).parent().toggleClass('expanded');
	if($(lnk).html() == 'посмотреть все')
		$(lnk).html('свернуть');
	else
		$(lnk).html('посмотреть все');
	$('#expand_catalog' + fid).toggle();
}

/* dealers functions */
function changeDealersRegion(url,sel, product){
	sel.blur();
	params = {'region': sel.value, 'update_list': 1}
	if(product){
		params.product = product;
	}
	ajaxLoadContent(url, 'dealers', params);
}

/* faq */
function showQuestions(wl_id, lnk){
	if($("#questions"+wl_id).css('display') != 'block'){
		$("#questions"+wl_id).animate({height: "show"}, 300);
	}else{
		$("#questions"+wl_id).animate({height: "hide"}, 300);
	}
	lnk.blur();
}

function formatIntValue(src){
	src = src.toString();
	var cnt = 1;
	var str = '';
	var lngth = 0;
	var res =  '';
	for(var i=src.length-1; i >= 0; i--){
		str += src.substr(i, 1);
		lngth++;
		if((src.length-i)%3 == 0 && i > 0){
			str += ' ';
			lngth++;
		}
	}	
	var t = '';
	for(var i=lngth-1; i>=0; i--){
		res += str.substr(i, 1);
	}
	return res;
}
