var lsOptions = {
    script:'/livesearch/',
    varName:'?q',
    json:true,
    showNoResults:true,
    maxResults:16,
    callback: function (obj) {
        $('#json_info').html('you have selected: '+obj.id + ' ' + obj.value + ' (' + obj.info + ')');
    }
};

function menuReady() {
    /*$('ul#globalnav li ul li ul').hide();*/ //for ie
    $('ul#globalnav li ul').hide();
    $('ul#globalnav li #product_menudiv').hide();
    var config = {
        sensitivity: 3,
        over: makeshow,
        timeout: 500,
        out: makehide
    };
    $('ul#globalnav li').hoverIntent(config);
}
function makeshow() {
    if ($(this).find('#product_menudiv').size() == 0) {
        $(this).find('ul:first').show();
    } else {
        $(this).find('#product_menudiv').show().find('ul').show();
    }
}
function makehide(e) {
    if ($(this).find('#product_menudiv').size() == 0) {
        $(this).find('ul:first').hide();
    } else {
        $(this).find('#product_menudiv').hide();
    }
}

function hidePopup(){
    $(".alertPopup").animate({
        opacity: 0
    }, 5000, function() {
        $(this).remove();
    });

}

function messageBox(title, message){

    var messageContainer=$("<div></div>").addClass("alertPopup");
    var titleContainer = $("<h3></h3>").text(title);
    if (message)
        var textContainer = $("<div></div>").addClass("text").html(message);
    //var linkContainer = $("<a href=\"/cart/\">Перейти в корзину</a>");

    messageContainer
    .append(titleContainer)
    
    if (message)
        messageContainer
        .append(textContainer);
    //.append(linkContainer);

    $("body").append(messageContainer);

    var t = setTimeout(hidePopup, 3000);

    return true;
}

function cartAnimate() {
    $("#bigpicture").animate({
        opacity: 0.25
      }, 500);

    $("#bigpicture").animate({
        opacity: 1
      }, 500);
    //alert ('animate');
}

function robocartmove() {
//    $("#robocartmove").css('margin-left','0px');
    thetop = ($(window).height()-93)+$(window).scrollTop();
//    alert (thetop);
    $("#robocart").css('top',thetop);
    theright = $(window).width();
    //alert (theright);
    $("#robocart").css('width',theright+300);
    
    $("#robocart").show();
    $("#robocartmove").css('margin-left','0px').show().delay(1).animate({marginLeft: theright+600},10000,function(){
        $("#robocart").fadeOut('slow');
        $("#robocartmove").css('margin-left','0px');
    }).fadeOut('slow');
    
    //$("#robocart").slideRight(1000);
    //alert ('left');
}

/*add to cart popup*/
  closePopups = function(popup, remove) {
	if (popup.length === 0) {
		popup = $('.thisispopup');
	}
	popup.fadeOut(300, function() {
		if (remove === true) {
			$(this).remove();
		}
    });
  };
  cartPopup = function(title, price, imgSrc) {
    var backLink, closeBtn, content, desc, footer, header, hidePopup, mainDiv, opnCartLink, preview, prvImg;
    closeBtn = $('<a href="#" class="close"></a>');
    header = $('<h4>Товар добавлен в корзину</h4>');
    prvImg = $('<img/>', {
      src: imgSrc,
      height: 80
    });
    preview = $('<div/>', {
      "class": 'popuppreview',
      html: $('<a/>').append(prvImg)
    });

    desc = $('<div/>', {
      "class": 'popupoverview',
      html: '<p class="price">' + price + '</p><p class="title"><b>' + title + '</b></p><p>Товаров в корзине: <a href="/cart.htm"><b><span class="cartGoods"></span></b></a><br>Сумма заказа: <a href="/cart.htm"><b><span class="total_price"></span> руб.</b></a></p>'
    });
    content = $('<div/>', {
      "class": 'popupcontent'
    });
    backLink = $('<a href="#" class="back"><span></span>Вернуться в каталог</a>');
    opnCartLink = $('<a href="/cart.htm" class="opencart"><span>Раскрыть корзину</span></a>');
    footer = $('<div/>', {
      "class": 'popupfooter'
    });
    mainDiv = $('<div/>', {
      "class": 'addtocartpopup thisispopup',
      html: '<div class="corner"/>'
    });
    hidePopup = 0;
    closeBtn.add(backLink).click(function(event) {
      event.preventDefault();
	  closePopups(mainDiv, true);
      // return mainDiv.fadeOut(300, function() {
      //   return $(this).remove();
      // });
    });
    mainDiv.mouseleave(function(event) {
      return hidePopup = setInterval(function() {
        return closeBtn.click();
      }, 1000);
    });
    mainDiv.mouseenter(function(event) {
      return clearInterval(hidePopup);
    });
	hidePopup = setInterval(function() {
		mainDiv.mouseleave();
	}, 8000);
		
    return mainDiv.append(header.append(closeBtn), content.append(preview, desc), footer.append(backLink, opnCartLink));
  };

showCartPopup = function(pos, title, price, imgSrc) {
    var newPos, popup, scrollPos;
    popup = cartPopup(title, price, imgSrc);
    $('body').prepend(popup.hide());
    newPos = {
	  top: pos.top - popup.outerHeight() - 5,
      left: pos.left - popup.outerWidth() + 50
    };

    popup.css({position:'absolute', top: newPos.top, left: newPos.left}).fadeIn('fast', function(){
		$('#inner').click(function(event) {
			event.preventDefault();
			$('.close',popup).click();
			$(this).unbind('click');
		});
	});

	scrollPos = $(window).scrollTop();
	if (scrollPos > popup.offset().top) {
		$.scrollTo(popup, 1100, {
			easing: 'easeOutCirc',
			offset: -20
	    });
	}
  };

function cart_binder () {
  addtocartLink = $('.addtocart');
  if (addtocartLink.length > 0) {
    addtocartLink.click(function(event) {
      var cartpop, obj, popup, preview, price, title;
      event.preventDefault();
      popup = $('body').find('.addtocartpopup');
      if (popup.length > 0) {
        popup.hide().remove();
      }
      cartpop = $('.cartpopup');
      if (cartpop.length > 0) {
        cartpop.fadeOut();
      }
      obj = $(this);
      title = obj.attr('alt');
      price = obj.attr('price');
      preview = obj.attr('preview');
      return showCartPopup(obj.offset(), title, price, preview);
    });
  }

    showCartIco = function() {
    var cartIcon;
    cartIcon = $('.price > .addtocart', $(this));
    if (cartIcon.length > 0) {
      return cartIcon.hide().fadeIn();
    }
  };
  hideCartIco = function() {
    var cartIcon;
    cartIcon = $('.price > .addtocart', $(this));
    if (cartIcon.length > 0) {
      return cartIcon.fadeOut();
    }
  };

  goodsBlock = $('.goods-list li');
  if (goodsBlock.length > 0) {
    goodsBlock.hover(showCartIco, hideCartIco);
    cartIcon = $('.price > .addtocart', goodsBlock);
    if (cartIcon.length > 0) {
      cartIcon.hide();
    }
  }
}

function addToCart(productId) {

    var _data="productId="+productId;

    $.post("/", _data, function(data){

        //messageBox('Добавлено', data.last.nomenklatura);
        cartAnimate();
        robocartmove();

        $("#cart_is_full").show();
        $("#cart_is_empty").hide();
        $("#header-cart").addClass("full");

        var existItem = false;

        $("ul.popupEmptyCart").hide();
        $("ul.popupFullCart").show();

        //$(".cart_box a.link").text("Ваша корзина (" + data.totalAmount + ")");
        $(".cartGoods").text(data.totalAmount);

        $(".cart_box ul.popupFullCart li").each(function(){
            if ($(this).attr("id") == "crt_"+data.id){
                $(this).find("div.amount span").html(data.amount);
                existItem=true;
                return false;
            }
        });

        if (existItem == false){
            $(".cart_box ul.popupFullCart").append("\n\
                <li id='crt_"+data.id+"'>\n\
                    <div class='img'>\n\
                        <img alt='"+data.last.nomenklatura+"' src='"+data.last.picture+"' width='50'>\n\
                    </div>\n\
                    <div class='desc'>\n\
                        <div class='title'>"+data.last.nomenklatura+"</div>\n\
                        <div class='amount'>Количество:&nbsp;<span>"+data.amount+"</span></div>\n\
                        <div class='price'>"+data.last.price+" р.&nbsp;</div>\n\
                    </div>\n\
                    <div class='clear'></div>\n\
                </li>");
        }

        $(".total_price").html(data.allSumFormated);
    }, "json");

    //cart_popup();
    
    return false;
}

/**
 * добавление продукта в список сравнения
 */
function addCompare(kod, tovcat) {
    $.post('/ajax/addcompare.htm','kod='+kod, function(json){
        if (json.result == true) {
            
            messageBox('Добавлено для сравнения', '<a href="/comparison.htm?categ='+tovcat+'" class="popup">Перейти к сравнению</a>');
        } else {
            messageBox('Этот продукт уже в списке сравнения', '<a href="/comparison.htm" class="popup">Перейти к сравнению</a>');
        }
    },'json');
}

/**
 * удалание продукта из списока сравнения
 */
function delCompare(kod, tovcat) {
    $.post('/ajax/delcompare.htm','kod='+kod, function(json){
        if (json.result == true) {
            messageBox('Исключено из сравнения', '<a href="/comparison.htm?categ='+tovcat+'"" class="popup">Перейти к сравнению</a>');
        }
    },'json');
}

function FFhide () {
    $('#FloatingFinder').fadeOut('fast');
}


function sendthisformwithajax (form) {
//    alert ($(form).html());
    formurl = $(form).action;
    $(form).append("<input type='hidden' name='ajaxed' value='1'>");
    $.post(formurl, $(form).serialize(), function(data) {
        alert (data);
        h = $(form).attr('tohide');
        if (h.length) $('#'+h).fadeOut('fast');
    });
//    alert ('ajaxed?');
    return false;
}

var FinderPosition = $('body').offset();

(function($) {

    $(document).ready(function() {
//        $('a[rel*=facebox]').facebox();

        $('[name="captcha"]').attr('autocomplete','off');
//        $('.captcha').attr('autocomplete','off');

        $('body').append("<div id='FloatingFinder'><img id='FloatingFinderClose' src='/img/closeicon.png'>Найдено <span class='FFTotal'><img src='/img/miniloader.gif'></span> <a id='FloatingFinderLink'>Показать</a></div>");

        cart_binder();

//        $("#ordercallform").submit(function(){
//            alert ('submit32');
//            return false;
//        });

        $("#FloatFinder").mouseleave(function(){
            setTimeout("FFhide()",4000);
        });
        $("#FloatingFinderClose").click(function(){
            FFhide();
            return false;
        });
        $("#FloatingFinderLink").click(function(){
            $('.price-filter>form').submit();
            return false;
        });

        $(".checkbox").click(function(){
            position = $(this).offset();
            FinderPosition = position;
//            alert ("left: " + FinderPosition.left + ", top: " + FinderPosition.top );
        });

        if ($('ul#globalnav li').length)
            menuReady();

        
        //main slideshow
        if ($('#carousel').length)
            $('#carousel').nivoSlider({
                pauseTime: 4000
            }); //effect:'fade',

        if ($('#horizontalList').length)
            $('#horizontalList').jcarousel();

        // popup cart items
        $('.cart_box').bind('mouseleave', function (e) {
            $('.cartPopUp').stop(false, true).fadeOut('fast');
            return false;
        });

        $('.cart_box').bind('mouseenter', function (e) {
            $(this).find('.hideBorder').width($(this).outerWidth() - 2);
            $('.cartPopUp').stop(false, true).fadeIn('fast').css({
                visibility: 'visible'
            });
            return false;
        });

        //раскраска таблиц
        if ($('.m-column table > tbody').length){
            $('.m-column table > tbody > tr:odd').addClass('odd');
        }

        //добавление товара к сравнению
        $(".addcompare").click(function(){
            //var kod=$(this).parent().attr('id');
            var kod=$(this).attr('kod');
            var moto=$(this).attr('type');
            var tovcat = $("a.goToCompare").attr('tt');
            if ($(this).hasClass('active')){
                delCompare(kod,tovcat);
                $(this).removeClass('active');            
                if (moto) {
                    $(this).html('<span>Сравнить с другими</span>');
                    if ($("#go_compare").attr('val')) $("#go_compare").hide();
                }
                else {
                    $(this).html("<span>Сравнить</span>");
                    itm2compare = itm2compare - 1;
                    $("#itm2compare").text(itm2compare);
                    if (itm2compare<1) $(".compare-pane").fadeOut();
                }
            } else {
                addCompare(kod, tovcat);
                $(this).addClass('active');
                if (moto) {
                    //$(this).addClass('instock');
                    $(this).html('<span>Добавлено к сравнению</span>');
                    $("#go_compare").show();
                }
                else {
                    $(".compare-pane").fadeIn();
                    $(this).html("<span>Выбрано</span>");
                    itm2compare = itm2compare + 1;
                    $("#itm2compare").text(itm2compare);
                }
            }         
            return false;
        });
       
        // печать
        // http://projects.erikzaadi.com/jQueryPlugins/jQuery.printElement/  - help here
        $("#doprint_card").click(function(){
//            $('#item-card').printElement({overrideElementCSS:['/css/style.css','/css/print.css']});
            $('#content').printElement({overrideElementCSS:['/css/style.css','/css/print.css']});
            //window.print();
            return false;
        });

//        Вход в личный кабинет
        $("#cabinetbutton").click(function(event){
			var popup = $('.authpopup');
			var closeBtn = $('.close', popup);
			closeBtn.click(function(event){
				event.preventDefault();
				closePopups(popup);
			});
			popup.fadeIn('fast', function(){
				$('#inner').click(function(event) {
					event.preventDefault();
					closeBtn.click();
					$(this).unbind('click');
				});
			});
            $('#pop_login').focus();
            return false;
        });

        // whatisit
        $(".whatisit").click(function(){
            text = $(this).attr('title');
            title = $(this).attr('val');
            messageBox(title,text);
            return false;
        });

        $("#doprint").click(function(){
            $('#content').printElement({overrideElementCSS:['/css/style.css','/css/print.css']});
            //window.print();
            return false;
        });
        
        //обработка Popup ссылок
        $("a.popup").live('click', function(){
            var href=$(this).attr('href');
            screenWidth=window.screen.width;
            screenHeight=window.screen.height;
            var comWin=window.open(href,'','height='+screenHeight+', width='+screenWidth+', scrollbars=yes');
            return false;
        });
        
        // открытие окна сравнения
        $(".goToCompare").click(function(){
            screenWidth=window.screen.width;
            screenHeight=window.screen.height;
            var categ = $(this).attr('tt');
            //alert (categ);
            var comWin=window.open('/comparison.htm?categ='+categ,'','height='+screenHeight+', width='+screenWidth+', scrollbars=yes');
            return false;
        });
        $('#i' + $('#filter-content a.selected').attr("index")).attr('checked', 'checked');

        $("#close-panel").click(function() {
            $('#top-panel').slideUp("slow");
            return false;
        });


        $("#open-adv-search").click(function() {
            if($('#adv-search').css('width')=='928px'){
                $('#adv-search').animate({
                    width:0
                }, function(){
                    $(this).hide();
                });

            } else {
                $('#adv-search').show();
                $('#adv-search').animate({
                    width:928
                });
                $('html,body').animate({
                    scrollTop: 100
                }, 1500);
            }
            return false;
        });

        $("#close-adv-search").click(function() {
            $('#adv-search').animate({
                width:0
            }, function(){
                $(this).hide();
            });
            return false;
        });

        $("#filter-content ul li a").click(function() {
            $('#i' + $('#filter-content a.selected').attr("index")).attr('checked', 'checked');
            $('#adv-search').animate({
                width:942
            });
            return false;
        });

        // manual tabs code
        if ($("#product-mnu a").hasClass("active")) {
            $($("#product-mnu a.active").attr("href")).css("display","block");
        } else {
            $("#product-mnu li:first a").addClass("active");
            $($("#product-mnu li:first a").attr("href")).css("display","block");
        }

        $("#product-mnu a").click(function() {
            if ($("#product-mnu a").hasClass("active")) {
                $($("#product-mnu a.active").attr("href")).css("display","none");
                $("#product-mnu  a.active").removeClass("active");
                $(this).addClass("active");
                $($(this).attr("href")).css("display","block");
            }
            return false;
        });

        $("#show-full-desc").click(function() {
            $("#show-full-desc").css({
                display:"none"
            });
            $("#hide-full-desc").css({
                display:"inline"
            });
            $("#full-desc").slideDown("slow");
            return false;
        });

        $("#hide-full-desc").click(function() {
            $("#hide-full-desc").css({
                display:"none"
            });
            $("#show-full-desc").css({
                display:"inline"
            });
            $("#full-desc").slideUp("slow");
            return false;
        });

        $("#accs_tab").click(function(){
            $("#first_tag_tab").click();
        });


        $(".acc_tab_button").click(function(){
            if ($(this).attr('loaded')==1) return false;
            this_a = $(this);
            filter = $(this).attr('categ');
            thisfilter = $(this).attr('thiscat');
            //test
            theitem = $(this).attr('item');
            tag = $(this).attr('tag');
//            alert (filter+' - '+item+' - '+tag);
            elemt = $('#tag'+tag).children('span');
            elemt.html($('#accs_loader').html());
            $.post('/product/tab_accs.htm', {categ: filter, item: theitem, thiscat: thisfilter}, function(data) {
                this_a.attr('loaded','1');
                elemt.hide().html(data).show('fast');
                $('.addtocart').unbind();
                cart_binder();
                //$('.addtocart').bind('click');
//                elemt.html(data);
                //alert (data);
            });
            return false;
        });

        $("#ordercalllink").click(function(){

            leftpos = $(this).offset();
//            alert (leftpos.left);
            $('#phonepopup').css('left',leftpos.left-40);
            $('#phonepopup').fadeToggle();
            return false;
        });

        var captcha_ok = false;
        $('#orderparameters').submit(function(){
            validation = validate_form();
            form = $(this);
            if (form.find('#captcha') && captcha_ok==false && validation) {
                ccode = form.find('#captcha').val();
                $.post('/ajax/check-captcha.htm',{captcha: ccode}, function(json) {
                    if (json.result==true) {
                        form.find('#captcha').removeClass('notvalid');
                        captcha_ok = true;
                        form.submit();
                    } else {
                        form.find('#captcha').addClass('notvalid');
                        form.find('#captcha').val('');
                        alert ('Неправильно введен код проверки CAPTCHA');
                        var timestamp = new Date().getTime();
                        form.find('#captcha_img').attr('src','/captcha/index.php?' +timestamp );
                        captcha_ok = false;
                    }
                },'json');
            }
            //alert (validation + ' ' + captcha_ok);
            if (validation && captcha_ok) return true;
            return false;
        });

        $('.orderparameters').submit(function(){
            validation = validate_form();
            form = $(this);
            if (form.find('#captcha') && captcha_ok==false && validation) {
                ccode = form.find('#captcha').val();
                $.post('/ajax/check-captcha.htm',{captcha: ccode}, function(json) {
                    if (json.result==true) {
                        form.find('#captcha').removeClass('notvalid');
                        captcha_ok = true;
                        form.submit();
                    } else {
                        form.find('#captcha').addClass('notvalid');
                        form.find('#captcha').val('');
                        alert (json.message);
//                        alert ('Неправильно введен код проверки CAPTCHA');
                        var timestamp = new Date().getTime();
                        form.find('#captcha_img').attr('src','/captcha/index.php?' +timestamp );
                        captcha_ok = false;
                    }
                },'json');
            }
            //alert (validation + ' ' + captcha_ok);
            if (validation && captcha_ok) {
                if ($(this).hasClass('ajaxed')) {
                    sendthisformwithajax(this);
                    return false;
                } else return true;
            }
            return false;
        });


        /*kunfuzi*/
        if ($("form#search-frm input[name=q]").length)
            $("form#search-frm input[name=q]").autoComplete(lsOptions);

        /*
        // tabs
        $("div.catalog-menu > ul > li > a").click(function(){
            $("div.catalog-menu > ul > li > a.active").removeClass("active");
            $(this).addClass("active");
            $("div.catalog-in.tab").hide();
            $("."+$(this).attr('rel')).show();
            $("h1 > span").text($(this).find("span").text());
            return false;
        });
*/
        $("form").bind('submit', function(){
            var result = true;
            $(this).find(".required").each(function(){
                if (!$(this).val()){
                    alert('Заполнены не все поля!');
                    $(this).focus();
                    return result = false;
                }
            });

            if (result) {
                $(this).find("input.password").each(function(){
                    var idChildElement=$(this).attr("rel");
                    if ($(this).val() != $("#"+idChildElement).val()){
                        alert('Пароли не совпадают!');
                        $(this).focus();
                        return result = false;
                    }
                });
            }

            return result;
        })

    });

})(jQuery);
