/* javascript */
$(document).ready(function(){
	
	// текущий раздел покажем
	obj = $(".selected").parent();
	if(!obj.is("li")) { obj = obj.parent(); }
	obj.find("ul:first").show();
	obj.find("a.open:first").toggleClass("close");
	for(i=0;i<10;i++){
		obj = obj.parent();
		if(obj.attr("class")=="start") break;
		obj = obj.parent();
		obj.find("a.open:first").toggleClass("close");
		obj.find("ul:first").show();
	}
	
	// показать/скрыть содержимое раздела
	$(".open").click(function(){
		// получим текущий li
		obj = $(this).parent();
		if(!obj.is("li")) obj = obj.parent();
		
		// покажем/скроем в текущме li первый ul
		$(this).toggleClass("close");
		obj.find("ul:first").toggle();
		
		return false;	
	});
	
        theRotator();
        
        // для страницы контактов добавим фильтр
        if($(".shops").is("div")) {
            // ага, добавляем
            // получим все округи
            filterOkrug = '<div class="select-shops"><span><p>Выберите округ:<p><select size="5" name="okrug" id="okrug" class="okrug">';
            $(".shops h2").each(function(){
                filterOkrug += '<option value="' + $(this).parent().attr("class") + '">' + $(this).text() + '</option>';
            });           
            filterOkrug += '</select></span></div><hr class="separator" />';
            $(".shops").prepend(filterOkrug);
            // скорем все магазины
            $(".shops ul li").hide();           
            $("#okrug").bind("change", changeOkrug);
            
            // после этого выберим текущий город по ip
            $(".shops li[for=ip]").each(function(){
                // нашли нужный округ и подставили
                $("#okrug").val($(this).attr("class"));
                $("#okrug").change();
                // найдем теперь нужный город и подставим
                $("#city").val($(".shops tr[for=ip]:first").attr("title"));
                $("#city").change();                
            });
        }
        
        // подключим lightbox, если нужно
        if($("a.lightbox").is("a")) {
            $('a.lightbox').lightBox({
                overlayBgColor: '#999',
                overlayOpacity: 0.6,
                imageLoading: '/upload/lightbox/loading.gif',
                imageBtnClose: '/upload/lightbox/close.gif',
                imageBtnPrev: '/upload/lightbox/prev.gif',
                imageBtnNext: '/upload/lightbox/next.gif',
                containerResizeSpeed: 350,
                txtImage: 'Фотография',
                txtOf: 'из',
            });         
        }
        
        // клик в прайсе
        $(".price .price-show-all").click(function(){
            $(".price .price-section").show();
            $(".price .price-open").addClass("price-close");
            return false;
        });
        $(".price .price-hide-all").click(function(){
            $(".price .price-section").hide();
            $(".price .price-open").removeClass("price-close");
            return false;
        });
        $(".price .price-open").click(function(){
            $(this).parent().parent().find(".price-section").toggle();
            $(this).toggleClass("price-close")
            return false;
        });
        
});

// смена округа
function changeOkrug(){
    // удалим выбор города, так как будет новый
    //if($(".shops ul").css("display")=="none") { console.log(1); $(".shops ul").show(); }
    
    $("select#city").remove();
    
    // скроем все и покажем только одну
    if($(this).val()=="#") {
        $(".shops li").show().find("tr").show();
        // уберем фильтр по городу и все
        reshowOdd();
        return false;
    } else {
        $(".shops li").hide();
        $(".shops li." + $(this).val()).show().find("tr").show();
    }    
    // выберим города, какие есть
    var city = [];
    $(".shops li." + $(this).val() + " tr").each(function(){
        if($(this).attr("title")) city.push($(this).attr("title"));
    });
    city = arrayUnique(city);

    filterCity = '<span><p>Выберите город:<p><select size="5" name="city" id="city" class="city">';
    for (i in city) filterCity += '<option value="' + city[i] + '">' + city[i] + '</option>';       
    filterCity += '</select></span>';
    
    $(".shops .select-shops span:first").after(filterCity);
    $("#city").bind("change", changeCity);   

    reshowOdd();
    return false;
}

// смена округа
function changeCity(){
    // скроем все и покажем только одну
    if($(this).val()=="#") {
        $(".shops li:visible tr").show();
    } else {
        $(".shops li:visible tr[class!=head]").hide();
        $(".shops li:visible tr[title='" + $(this).val() + "']").show();
    }
    
    // перерисуем четные и нечетные
    $(".shops li tr:visible[class!=head]").each(function(i){
        if(i%2==0)
            $(this).addClass("odd");
        else
            $(this).removeClass("odd");
    });
    return false;
}

function reshowOdd(){
    // перерисуем четные и нечетные для всего
    $(".shops li:visible").each(function(){
        $(this).find("tr:visible[class!=head]").each(function(i){
            if(i%2==0)
                $(this).addClass("odd");
            else
                $(this).removeClass("odd");
        });
    });
}

// с карты выбор региона
function mapOkrug(id){
    $("select#okrug option[value=okrug" + id + "]").attr("selected","1");
    $("#okrug").change();
}

// проверка формы на заполнение обязательных полей
function checkField(){
	$(".requiredfield").removeClass("requiredfield");
	ok = true;
	$("span.starrequired").each(function(){
		obj = $(this).parent().find(".text");
		if(obj.is("input") || obj.is("textarea")) {
			if(!obj.val().length>0) {
				ok = false;
				obj.stop()
					.css({ 'position': 'relative', 'left': '0px' })
					.animate({ left: "20px" }, 100)
					.animate({ left: "0px" }, 100).animate({ left: "20px" }, 100)
					.animate({ left: "0px" }, 100).addClass("requiredfield"); 
			}
			
		}
	});
	
	return ok;
}

// сделаем смены фона в шапке
function theRotator() {
    if($('.bg-header').length>1) {
	$('.bg-header').css({ 'opacity': '0.0' }).show();
	$('.bg-header:first').css({ 'opacity': '1.0' }).addClass("bg-header-current");
	setInterval('rotate()',5000);
    }
}
function rotate() {
    var current = $(".bg-header-current") || $('.bg-header:first');
    var next = (current.next().is("img") ? current.next() : $('.bg-header:first'));
    next.css({ 'opacity' : '0.0'}).animate({opacity: 1.0}, 1000).addClass("bg-header-current");
    current.animate({ 'opacity' : '0.0'}, 1000).removeClass("bg-header-current");
};

// выбирать уникальные значения
function arrayUnique( ar ) {
    var a = [];
    var l = ar.length;
    for(var i = 0; i < l; i++) {
        for(var j = i+1; j < l; j++) {
            if (ar[i] === ar[j]) j = ++i;
        }
        a.push(ar[i]);
    }
    return a;
}


