/**
 * @author Semen Pupkov
 * @copyright Clever Studio (www.clever-site.ru)
 * Edited by ss831 and maxres
 */

// Global vars
var curColorNumber = 0;
var OPT_KOLVO = 11;

/**
 * Увеличение / Уменьшение картинки в карточке
 */
function imageZoom(image, multiply, type, limit)
{
    var curWidth = $(image).width();
    var curHeight= $(image).height();
    var coords = $(image).position();
    var newWidth = curWidth;
    var newLeft = coords.left;
    var newTop = coords.top;

    // Увеличиваем
    if( (type == 'in') && curWidth < limit ){
        newWidth = (curWidth * multiply);
        newLeft = coords.left - ( (newWidth - curWidth) / 2);
        newTop = coords.top - (newWidth - curWidth);

    }
    // Уменьшение
    if( (type == 'out') && curWidth > limit){
        newWidth = curWidth / multiply;
        newLeft = coords.left + ((curWidth - newWidth) / 2);
        newTop = coords.top + (curWidth - newWidth );
    }

    var cssProps = {
        'width': newWidth.toFixed(0)*1,
        'left' : newLeft.toFixed(0)*1,
        'top'  : newTop.toFixed(0)*1
    }
    $(image).css(cssProps);

}

/**
 * Форматирует число
 * @param {Number} nStr Форматируемое число
 * @param {String} inD The decimal character for the input, such as '.' for the number 100.2
 * @param {String} inD The decimal character for the output, such as ',' for the number 100,2
 * @param {String} inD  The separator character for the output, such as ',' for the number 1,000.2
 * addSeparatorsNF('52093423.003', '.', ',', '.')
 * 52.093.423,003
*/
function addSeparatorsNF(nStr, inD, outD, sep)
{
	nStr += '';
	var dpos = nStr.indexOf(inD);
	var nStrEnd = '';
	if (dpos != -1) {
		nStrEnd = outD + nStr.substring(dpos + 1, nStr.length);
		nStr = nStr.substring(0, dpos);
	}
	var rgx = /(\d+)(\d{3})/;
	while (rgx.test(nStr)) {
		nStr = nStr.replace(rgx, '$1' + sep + '$2');
	}
	return nStr + nStrEnd;
}

function recalcOrderWin()
{

       var total_count = 0;
       var total_price = 0;
       var tmp_total_count = 0;
       // ---------------
       if(no_sale == 'y' || price_type == 'new'){
            // Если нет скидки и цена новая това считаем по base_price
            row_price = base_price;
       }
       else{
          $('table.orders tbody tr').each(function(i, e){
                 var tmp_row_count = $(e).find('input.count').val();
                 tmp_total_count = tmp_total_count + tmp_row_count*1;

          });

           //alert(temp_total);
           if( (tmp_total_count*1) >= OPT_KOLVO ){

                row_price = opt_price;
           }
           else{
                row_price = base_price;
           }

       }
       // -----------------
       $('table.orders tbody tr').each(function(i, e){
            //var row_price = $(e).find('span.price-val').text();

            var row_count = $(e).find('input.count').val();
            var rgx = /( )/;
            while (rgx.test(row_price)) {
                row_price = row_price.replace(/( )/g, "");
            }

            $(e).find('td.count em').text(row_price);
            $(e).find('span.price-val').text( addSeparatorsNF( (row_price * row_count), '.', '.', ' ')).attr('rel', (row_price * row_count));

            total_count = total_count + row_count*1;
            total_price = total_price + row_price*row_count;

       });


       // ---------------

       if(no_sale == 'n'){
           if( (tmp_total_count*1) >= OPT_KOLVO ){
                if(sale_val > 0){
                   var sale_count = total_price * sale_val / 100;
                   var sale_row = 'Скидка <span id="sale_value">'+sale_val+'</span>% <span id="sale_count">'+(sale_count)+'</span> Р<span class="rub-line">&mdash;</span>';
                   total_price = total_price - sale_count;
                   $('#sale').html(sale_row);
                }
                

           }
           else{
                $('#sale').html(' ');
           }
       }

       // -----------------

       $('table.orders tfoot strong.total_count').text(addSeparatorsNF(total_count, '.', '.', ' '));
       $('#total_price').text(addSeparatorsNF(total_price, '.', '.', ' '));
}

/*
 * Пересчитывает цены в зависимости от скидки
 */
function calcSales()
{
    var total_price = $('#total_price').text().replace(/( )/g, "");
    var total_count = $('table.orders tfoot strong.total_count').text().replace(/( )/g, "");
    var sale_count = 0;
    var sale_value = 0;
    var sale_row;

    if(adv_sale > 0){

        sale_count = total_price * adv_sale / 100;
        sale_row  = 'Скидка <span id="sale_value">'+adv_sale+'</span>% <span id="sale_count">'+sale_count+'</span> Р<span class="rub-line">&mdash;</span>';
        total_price = total_price - sale_count;
        $('#sale').html(sale_row);
        $('#total_price').text(addSeparatorsNF(total_price, '.', '.', ' '));
    }
    else{
        $.each(sales, function(i,n){
        if( (total_count >= sales[i].start_count) && (total_count <= sales[i].finish_count) ){
            sale_value = sales[i].sale_value*1;
            sale_count = total_price * sales[i].sale_value / 100;

            total_price = total_price - sale_count;
            sale_count = addSeparatorsNF(sale_count, '.', '.', ' ');

            if(sale_value > 0){
                sale_row  = 'Скидка <span id="sale_value">'+sale_value+'</span>% <span id="sale_count">'+sale_count+'</span> Р<span class="rub-line">&mdash;</span>';
                $('#sale').html(sale_row);
                $('#total_price').text(addSeparatorsNF(total_price, '.', '.', ' '));
            }

            return false;
        }
        else{
            $('#sale').html(' ');
            //return false;
        }
    });
    }
}

function advCalcSales(total_price, total_count)
{
    var sale_count = 0;
    var sale_value = 0;
    var sale_row;
    if(adv_sale > 0){

        sale_count = total_price * adv_sale / 100;
        sale_row  = 'Скидка <span id="adv-sale-value">'+adv_sale+'</span>% <span id="adv-sale-count">'+sale_count+'</span> Р<span class="rub-line">&mdash;</span>';
        total_price = total_price - sale_count;
        $('#adv-sale').html(sale_row);
        $('#adv-total-price').text(addSeparatorsNF(total_price, '.', '.', ' '));

    }
    else{
        $.each(sales, function(i,n){
            if( (total_count >= sales[i].start_count) && (total_count <= sales[i].finish_count) ){
                sale_value = sales[i].sale_value*1;
                sale_count = total_price * sales[i].sale_value / 100;

                total_price = total_price - sale_count;
                sale_count = addSeparatorsNF(sale_count, '.', '.', ' ');

                if(sale_value > 0){
                    sale_row  = 'Скидка <span id="adv-sale-value">'+sale_value+'</span>% <span id="adv-sale-count">'+sale_count+'</span> Р<span class="rub-line">&mdash;</span>';
                    $('#adv-sale').html(sale_row);
                    $('#adv-total-price').text(addSeparatorsNF(total_price, '.', '.', ' '));
                }

                return false;
            }
            else{
                $('#adv-sale').html(' ');
                $('#adv-total-price').text(addSeparatorsNF(total_price, '.', '.', ' '));

                //return false;
            }

        });
    }

}

function recalcMainBasket()
{

    var lat_item_price = $('#table_orders_list td.summa em:last').text().replace(/( )/g, "");
    var total_price = $('#table_orders_list td.total-price-val em').text().replace(/( )/g, "");
    var total_count = $('#table_orders_list td.total-count').text();

    //alert(total_count);

    total_count = total_count*1;
    total_price = parseFloat(total_price);
    lat_item_price = parseFloat(lat_item_price);

    total_price = (total_price).toFixed(2).replace(".", ",");

    $('#table_orders_list td.total-price-val em').text(addSeparatorsNF(total_price, '.', '.', ' '));
    $('#table_orders_list td.total-count').text(total_count);
    $('#basket-line strong:first').text(total_count);
    $('#basket-line strong:last').text(addSeparatorsNF(total_price, '.', '.', ' '));


    if($('#basket-line p').attr('class') == 'empty'){
        $('#basket-line p').html('<span><a href="/user/orders/basket/">В корзине</a>:</span>&nbsp;&nbsp;&nbsp;<strong>'+(total_count + 1)+'</strong>&nbsp;товар&nbsp;на сумму <strong>'+addSeparatorsNF(total_price, '.', '.', ' ')+' р.</strong>');
        $('#main-basket-wrap div.controls').html('<div class="check"><input type="checkbox" id="agree" name="agree" value="y" />&nbsp;<label for="agree">Я согласен с </label><a class="pseudo-link" href="/purchase-terms/e-commerce/">условиями магазина</a></div><a id="go-order-link" class="disabled" href="/user/orders/basket/order-process.php"><img src="/bitrix/templates/main/images/confirm-order-btn-disabled.png" alt="Подтвердить заказ" /></a><a href="/user/orders/basket/?action=clear"><img src="/bitrix/templates/main/images/del-btn.png" alt="Удалить"></a>');
    }


}

function changeimage(img, n, count, mbanner_timeout)
{

   $('#main-image').fadeOut('slow', function(){
        $('#main-image').css({"background":"url("+img[n].src+")"})
        $('#main-image').fadeIn('slow', function(){});
   });

   //$('#main-image').css({"background":"url("+img[n].src+")"})

    n++;
    if (n<0) {n=0}
    if (n>count) {n=0}

    setTimeout(function(){
        changeimage(img, n, count, mbanner_timeout)
    }, mbanner_timeout);
}

function mtRand(min, max)
{
    var range = max - min + 1;
    var n = Math.floor(Math.random() * range) + min;
    return n;
}

/**
 * Генератор случайного парол
 */
function mkPass(len)
{
    var len=len?len:14;
    var pass = '';
    var rnd = 0;
    var c = '';
    for (i = 0; i < len; i++) {
        rnd = mtRand(0, 2); // Латиница или цифры
        if (rnd == 0) {
            c = String.fromCharCode(mtRand(48, 57));
        }
        if (rnd == 1) {
            c = String.fromCharCode(mtRand(65, 90));
        }
        if (rnd == 2) {
            c = String.fromCharCode(mtRand(97, 122));
        }
        pass += c;
    }
    return pass;
}


function insMap(obj, mar){
    var markers=new Array();
    var marr=new Array();
    markers[1]={id:1,x:mar.lat,y:mar.lon,html:mar.url};
    var country=1;

    var baseIcon = new GIcon();
    baseIcon.shadow = "";
    baseIcon.iconSize = new GSize(mar.icon.width, mar.icon.height);
    baseIcon.iconAnchor = new GPoint(mar.icon.offset_x, mar.icon.offset_y);
   // baseIcon.infoWindowAnchor = new GPoint(9, 100);
   // baseIcon.infoShadowAnchor = new GPoint(9, 50);



     if (GBrowserIsCompatible()) {
         var map = new GMap2(document.getElementById(obj));
         map.setCenter(new GLatLng(mar.lat, mar.lon), 16);

        var point = new GLatLng(markers[1].x, markers[1].y);
         marr[1] = createMarker(point, 1, markers[1].html);
         map.addOverlay(marr[1]);
     }

    function createMarker(point, index, html) {
        var letteredIcon = new GIcon(baseIcon);
        letteredIcon.image = mar.icon.path;

        markerOptions = {icon:letteredIcon};
        var marker = new GMarker(point, markerOptions);

        if (country) {
        GEvent.addListener(marker, "click", function() {
        document.location=html;
        });

        } else {
        GEvent.addListener(marker, "click", function() {
        marker.openInfoWindowHtml(html);
        });
        }
        return marker;
    }

}


$(function(){


    $('#submenu .menu-item').hover(function(){
        $(this).addClass('hover');
    },function(){
        $(this).removeClass('hover');
    });

    // News Carusel
    $('#news-list').jcarousel({scroll: 3});
    $('.jcarousel-container').prepend('<div class="clearer"></div>');

    // Drop-list in orders
    $('table.orders i.d-arrow-ico').live('click', function(){

        var listName = $(this).parent().parent().attr('class');
        listName = listName.split(' ');
        var list = '#'+listName[0]+'-list';
        var listClass = 'div.'+listName[0]+'-list';
        var listWidth = $(list).width();
        var p = $('#orders-table-wrap').offset();
        var c = $(this).offset();
        var cssDisplay;

        $('i.d-arrow-ico').css('z-index', '0');
        $(this).css('z-index', '200');

        cssDisplay = "none";
        if($(list).css('display') == 'none'){
            cssDisplay = "block";
            $(list).addClass('display');
        }

        if($(list).css('display') == 'block'){
            cssDisplay = "none";
            $(list).removeClass('display');
        }

        var left;
        if( $('div.list').hasClass('list-cols3')){
            left = c.left - p.left -10;
        }
        else{
            left = (c.left - p.left) - listWidth + 20;
        }

        var cssProps = {
            "display" : cssDisplay,
            "left" : left,
            "top" : c.top - p.top - 4
        }

        $(this).css('z-index', '200');
        $(list).css(cssProps);

        $('table.orders td.change').removeClass('change');
        // Смена класса родителя
        var parent_td = $(this).parents('td');
        $(parent_td).toggleClass('change');

    });

    // Выбор из списка
    $('div.list li').live('click', function(){

       var list = $(this).parents('div.list');
       var inner_content = $(this).find('div').html();
       var value = $(this).attr('rel');
       var el_style = $(this).find('div').css('background');
       var el_color = $(this).find('div').css('color');
       $('td.change input').val(value);

       $('table.orders td.change div.wrap div').html(inner_content).css({'background': el_style, "color": el_color});
       $('table.orders td.change').toggleClass('change');
       $(list).hide();


    });

    // Catalog list pp-win
    $('#catalog-list ins.item a').live('mouseover', function(){

        var catalogItem = $(this).parents('ins');
        $(this).parents('ins').addClass('hover');

        var wrap_coords = $('#catalog-list').offset();
        var coords = catalogItem.offset();

        var cssParams = {
            "display" : "block",
            "left" : coords.left - wrap_coords.left + 8,
            "top" : coords.top - wrap_coords.top - 35
        }

        $('#item-pp-win').attr('href', $(catalogItem).find('a').attr('href'));
        $('#item-pp-win').css(cssParams);

    });

    $('#item-pp-win').live('mouseout', function(){
        //$(this).parents('ins').removeClass('hover');
        $('#catalog-list ins').removeClass('hover');
        $('#item-pp-win').hide();
    });

    /**
     * Order-btn pp-win
     * Всплывающие окно при клике на кнопку заказать
     * в карточке товара
     */
    $('div.order-btn a').click(function(){
        $('#adv-order-win').show();
        return false;
    });

    // Close Simple order Win
    $('#simple-order-close').click(function(){
        $('#simple-order-list, div.list').hide();
    });

    // Add new row
    $('#add-row').click(function(){

       $('div.list').hide();
       var num_rows = $('table.orders tbody tr').length*1 + 1;

       var summa = $('table.orders td.summa:first span.price-val').attr('rel');
       var price = $('table.orders td.count:first em').text();
       var color = $('table.orders td.color:first').html();
       var size = $('table.orders td.size:first').html();

       color = color.replace(/\[(\d+)]/g, '['+num_rows+']');
       size = size.replace(/\[(\d+)]/g, '['+num_rows+']');

       var rowTemplate = '<tr>\n\
                            <td class="color">'+color+'</td>\n\
                            <td class="size">'+size+'</td>\n\
                            <td class="count">\n\
                                <input class="count" type="text" value="1" name="items['+num_rows+'][count]" maxlength="3" />\n\
                                    <span><i class="ico cross-ico"></i>&nbsp;<em>'+price+'</em>&nbsp;&nbsp;&nbsp;=</span>\n\
                                    <input type="hidden" value="'+price+'" name="items['+num_rows+'][price]" class="price-val">\n\
                            </td>\n\
                            <td class="summa">\n\
                                <span rel="'+summa+'" class="price-val">'+summa+'</span>&nbsp;Р<span class="rub-line">=</span>\n\
                            <input type="hidden" value="'+summa+'" name="items['+num_rows+'][total-price]" class="total-price-val">\n\
                            </td>\n\
                            <td class="del"><div><span>Удалить</span><i class="ico del"></i></div></td>\n\
                         </tr>';

       // Добавляем строку
       $(rowTemplate).insertAfter('table.orders tbody tr:last-child');

      recalcOrderWin();
      //calcSales();

    });

    // Удаление строки
    $('table.orders td.del div').live('click', function(){
        var parent_tr = $(this).parents('tr:first');
        //var index = $('table.orders tr').index(parent_tr);
        var count = $('table.orders tbody tr').length;

        if(count > 1){
            $(parent_tr).replaceWith('');
            recalcOrderWin();
            calcSales();
        }
    });
    // Пересчет цен при изменении количеста
    $('input.count').live('keyup', function(){
        //var count = $(this).val();
        //var parent_td = $(this).parent();
        //var parent_tr = $(parent_td).parent();
        //var price =  $(parent_td).find('em').text();
        //var price_wrap = $(parent_tr).find('span.price-val');


        //$(price_wrap).text(addSeparatorsNF((price * count), '.', '.', ' '));
        recalcOrderWin();
        //calcSales();

    });


    // Adv order win
    $('#adv-order-win input.adv-count').live('keyup', function(){
        if(is_1C){
            if($(this).val()*1>$(this).attr('data-qty')*1) $(this).val($(this).attr('data-qty'));

            var total_count=0;
            var total_price=0;

            $('#adv-order-win input.adv-count').each(function(i,e){total_count+=$(e).val()*1});

            //if(price_type=='new') $('#adv-order-win input.adv-count').each(function(i,e){total_price+=$(e).val()*$(this).attr('data-npr')});
            //else if(no_sale=='n' && total_count>=OPT_KOLVO) $('#adv-order-win input.adv-count').each(function(i,e){total_price+=$(e).val()*$(this).attr('data-opr')});
            if(total_count>=OPT_KOLVO) $('#adv-order-win input.adv-count').each(function(i,e){total_price+=$(e).val()*$(this).attr('data-opr')});
            else $('#adv-order-win input.adv-count').each(function(i,e){total_price+=$(e).val()*$(this).attr('data-bpr')});

            if(no_sale=='n'){
                if(total_count>=OPT_KOLVO){
                    if(sale_val>0){
                        var sale_count=total_price*sale_val/100;
                        var sale_row='Скидка <span id="sale_value">'+sale_val+'</span>% <span id="sale_count">'+sale_count+'</span> Р<span class="rub-line">&mdash;</span>';
                        total_price=total_price-sale_count;
                        $('#adv-sale').html(sale_row);
                    }
                }else{
                    $('#adv-sale').html(' ');
                }
            }

            $('#adv-total span.count').text(total_count);
            $('#adv-total-price').text(addSeparatorsNF(total_price,'.','.',' '));
        }else{
            var total_count = 0;
            var price = $('#adv-product-price').text()*1;
            var total_price = 0;

            $('#adv-order-win input.adv-count').each(function(i,e){
                var qty = $(e).val()*1; 
                var stg = $(e).attr('data-quantity')*1;
                if(qty>stg){
                    qty = stg;
                    $(e).val(stg);
                }
                total_count = total_count + qty;
            });


            if(no_sale == 'y' || price_type == 'new'){
               // Считаем по base_price
               price = base_price;

            }
            else{
                if(total_count >= OPT_KOLVO){
                    price = opt_price;
                }
                else{
                    price = base_price;

                }
            }


            total_price = total_count * price;

            if(no_sale == 'n'){
               if( total_count >= OPT_KOLVO ){
                    if(sale_val > 0){
                       var sale_count = total_price * sale_val / 100;
                       var sale_row = 'Скидка <span id="sale_value">'+sale_val+'</span>% <span id="sale_count">'+(sale_count)+'</span> Р<span class="rub-line">&mdash;</span>';
                       total_price = total_price - sale_count;
                       $('#adv-sale').html(sale_row);
                    }


               }
               else{
                    $('#adv-sale').html(' ');
               }
           }

            $('#adv-total span.count').text(total_count);
            $('#adv-product-price').text(price);
            
            $('#adv-total-price').text(addSeparatorsNF(total_price, '.', '.', ' '));
            //advCalcSales(total_price, total_count);
        }
    });


    $('#adv-order-add').click(function(){
        $('#adv-add').click();
    });


    // Переключение Цветов в карточке товара
    $('#colors div.color').click(function(){
        $('#colors div.row').removeClass('active');
        $(this).parent('div').addClass('active');
        //var divClass = $(this).parent('div').attr('class').split(" ");
        var bgImage = $(this).attr('rel');
        var cssParams = {
            "background" : "url("+bgImage+") no-repeat"

        }
        $('#rotate-image').css(cssParams);
    	curColorNumber = $('#colors div.active span').html();
    });
    
    // TODO: Костыль для обработки бага с незагрузкрй картинки при первом переходе
	var k_bgImage = $('#colors div.active div.color').attr('rel');
	var k_cssParams = {"background" : "url("+k_bgImage+") no-repeat"};
	$('#rotate-image').css(k_cssParams);


    // Увеличение картинки


    // Поворот майки
    // Поворот вправо
    $('#r-right').mousehold(50, function(){
       var pPosition = $('#rotate-image').attr('class');
       pPosition = pPosition.split('-');
       var newPosition = (pPosition[1])*1 + 1;
       if(pPosition[1] >= 12){
           newPosition = 1;
       }
       $('#rotate-image').removeClass(pPosition[0]+'-'+pPosition[1]).addClass(pPosition[0]+'-'+newPosition);
       $('#c-position').removeClass(pPosition[0]+'-'+pPosition[1]).addClass(pPosition[0]+'-'+newPosition);
    });
    // Поворот Влево
    $('#r-left').mousehold(50, function(){
       var pPosition = $('#rotate-image').attr('class');
       pPosition = pPosition.split('-');
       var newPosition = (pPosition[1])*1 - 1;
       if(pPosition[1] <= 1){
           newPosition = 12;
       }
       $('#rotate-image').removeClass(pPosition[0]+'-'+pPosition[1]).addClass(pPosition[0]+'-'+newPosition);
       $('#c-position').removeClass(pPosition[0]+'-'+pPosition[1]).addClass(pPosition[0]+'-'+newPosition);
    });
    
	// Перетаскивание
	$('#rotate-image,#c-position').css('cursor','e-resize').mousedown(function(e){
		var mouse_x=e.pageX;
		$('body').mousemove(function(e){
			var dx=e.pageX-mouse_x;
			if(Math.abs(dx)>16){
				mouse_x=e.pageX;
				if(dx>0){
					var pPosition = $('#rotate-image').attr('class');
					pPosition = pPosition.split('-');
					var newPosition = (pPosition[1])*1 + 1;
					if(pPosition[1] >= 12){
						newPosition = 1;
					}
					$('#rotate-image').removeClass(pPosition[0]+'-'+pPosition[1]).addClass(pPosition[0]+'-'+newPosition);
					$('#c-position').removeClass(pPosition[0]+'-'+pPosition[1]).addClass(pPosition[0]+'-'+newPosition);
				}
				if(dx<0){
					var pPosition = $('#rotate-image').attr('class');
					pPosition = pPosition.split('-');
					var newPosition = (pPosition[1])*1 - 1;
					if(pPosition[1] <= 1){
						newPosition = 12;
					}
					$('#rotate-image').removeClass(pPosition[0]+'-'+pPosition[1]).addClass(pPosition[0]+'-'+newPosition);
					$('#c-position').removeClass(pPosition[0]+'-'+pPosition[1]).addClass(pPosition[0]+'-'+newPosition);
				}
			}
			return false;
		}).mouseup(function(){
			$(this).unbind('mousemove').unbind('mouseup').unbind('mouseleave');
			return false;
		}).mouseleave(function(){
			$(this).unbind('mousemove').unbind('mouseup').unbind('mouseleave');
			return false;
		});
		return false;
	});



   // Main menu activate
   $('#mainmenu li a').click(function(){
       var parent_li = $(this).parent('li');
       var index = $('#mainmenu li').index(parent_li);
       $('#mainmenu li').removeClass('active').removeClass('active-last').removeClass('active-first').removeClass('active-print');
       $(parent_li).addClass('active');

       // Если элемент последний, последниму тоже сделаем активный бэкграунд

       // Если элемент первый
       if(index == 0){
            $('#mainmenu li:first').addClass('active-first');
       }
       if(index == 7){
            $('#mainmenu li:last').addClass('active-print');
       }
   });

   $('#simple-order-add').click(function(){
      $('#add-to-basket-btn').click();
   });

   $('#reg-btn').click(function(){
        $('#submit').click();
        return false;
   });

   $('#fiz-reg-btn').click(function(){
        $('#fiz-submit').click();
        return false;
   });

   $('#use-email-login').click(function(){
       $('#login').val($('#email').val());
   });

   $('#fiz-use-email-login').click(function(){
       $('#fiz-login').val($('#fiz-email').val());
   });

   $('#pass-generator').click(function(){
       var pass = mkPass(mtRand(10, 14));
       $('#pass').val(pass);
       $('#confirm').val(pass);

   });

   $('#fiz-pass-generator').click(function(){
       var pass = mkPass(mtRand(10, 14));
       $('#fiz-pass').val(pass);
       $('#fiz-confirm').val(pass);

   });

   // Adv order Win
   $('#adv-order-win div.w').hover(function(){
       $(this).addClass('hover');
   }, function(){
       $(this).removeClass('hover');
   });

   $('#adv-order-win div.w').click(function(){
        $('#adv-order-win div.w').removeClass('active');
        $(this).addClass('active');

        var inp = $(this).find('input');
        $('#adv-order-win input').hide();
        $('#adv-order-win span').show();
        $(this).find('span').hide();
        $(inp).show();
        $(inp).focus();


   });
   $('#adv-order-win div.w input').blur(function(){
      $(this).prev('span').text($(this).val());
   });

      // Feedback
   $('#fl').click(function(){
        $('#feedback').show();
        $('#feedback').animate({top: 0}, '1000', 'linear');
        return false;
   });

   $('#close-feedback').click(function(){
        $('#feedback').animate({top: -520}, '1000', 'linear');
   });

   $('#send-message').click(function(){
        if($('#feedback textarea').val() == ''){
            $('#feedback textarea').addClass('error');
        }
        else{

            var params = {
                'name' : $('#name').val(),
                'email': $('#email').val(),
                'phone': $('#phone').val(),
                'message' : $('#message').val()
            }

            $.ajax({
                type: "POST",
                data : params,
                url: "/bitrix/templates/.default/helpers/ajax/feedback.php",
                success:function(result){
                    $('#feedback').animate({top: -520}, '1000', 'linear', function(){$('#feedback .input').val('')});
                }
            });
        }

        });

      $('#feedback textarea').click(function(){
          $(this).removeClass('error');
      });

      $('#adv-order-win i.toggle2').click(function(){
         $('#adv-order-win').hide();
         $('#simple-order-list').show();
      });

      $('#simple-order-list i.toggle1').click(function(){
         $('#adv-order-win').show();
         $('#simple-order-list').hide();
      });

      $('#adv-order-close').click(function(){
            $('#adv-order-win').hide();
      });
      
            
      /* Enter */
       $('#enter-link').click(function(){
            $('#login-form').show();
            $('#login-form').animate({top: 0}, '1000', 'linear');
            return false;
       });

       $('#close-login').click(function(){
           //$('#login-form').removeClass('login-error');
           $('#login-form').animate({top: -330}, '1000', 'linear');
       });
       $('#enter-btn').click(function(){
           $('#submit-login').click();
       });

       // Material
       $('div.material a').click(function(){
            var params = {
                'id' : $(this).attr('rel')
            }
            var w_coords = $('#wrap').offset();
            var coords = $(this).offset();

            $.ajax({
                type: "POST",
                data : params,
                url: "/bitrix/templates/.default/helpers/ajax/material.php",
                success:function(result){
                    var template = '<div style="left: '+(coords.left - w_coords.left - 20)+'px;top: '+(coords.top - w_coords.top - 20)+'px;" id="material-win" class="d-shadow"><div class="d-shadow-wrap"><div class="body"><div class="close-cross"></div>'+result+'</div><div class="d-sh-cn d-sh-tl"></div><div class="d-sh-cn d-sh-tr"></div></div><div class="d-sh-cn d-sh-bl"></div><div class="d-sh-cn d-sh-br"></div></div>';
                    $('#wrap').append(template);
                }
            });

           return false;
       });

       $('div.close-cross').live('click', function(){
           $(this).parents('div.d-shadow').remove();
       });

       // Contacts
       $('div.contacts ins.pseudo-link').click(function(){

           $('#map-win').remove();
           var city = $(this).parents('div.section').find('h2').text();
           var street = $(this).text();
           var descr = $(this).parents('ins.col').find('h3').text();

           var coords = $(this).attr('rel');
           coords = coords.split(',');
           var link_coords = $(this).offset();
           var win_left = '55';

       //    if(link_coords.left > 700){
       //         win_left = link_coords.left - 600;
       //    }
       //    else{
       //        win_left = link_coords.left - 300;
       //    }
       		

           var lat = coords[0];
           var lon = coords[1];
           link_coords.top = link_coords.top - 90;

           var template = '<div style="left: '+(win_left)+'px;top: '+link_coords.top+'px;" id="map-win" class="d-shadow"><div class="d-shadow-wrap"><div class="body"><div class="adress-header"><div class="close-cross"></div><span class="adress-print">Печатать страницу</span><h2 class="adress-title"><i class="ico"></i><strong>'+descr+'.</strong> '+city+', '+street+'</h2></div><div id="map"></div></div><div class="d-sh-cn d-sh-tl"></div><div class="d-sh-cn d-sh-tr"></div></div><div class="d-sh-cn d-sh-bl"></div><div class="d-sh-cn d-sh-br"></div></div>';
           $('#wrap').append(template);

           var icon = {"path":"/bitrix/templates/main/images/map-logo.png", "width":80, "height":41, "offset_x":15, "offset_y":100};
           var marker = {"lat":lat, "lon":lon, "url":"/contacts/", "icon":icon};

           insMap('map',marker);
       });

       $('img.save').click(function(){
           $(this).next().click();
       });

       $('img.edit-profile').click(function(){
            $('div.show').css({'display': 'none'});
            $('.hidden').removeClass('hidden');
            $(this).addClass('save').attr('src','/bitrix/templates/main/images/save-btn.png');
            $(this).addClass('hidden');
       });

       //Обновление количества в корзине

        $('#table_orders_list td.art i.ico').live('click', function(){
          $(this).parents('tr').toggleClass('change_row');

        });

        // Изменение товара в корзине
       $('#art-list li').live('click', function(){

            var id = $(this).attr('rel');
            var count = $('tr.change_row td.count input').val();
            var update_id = $('tr.change_row td.art div.art-name').attr('rel');

            var params = {
              id : id,
              count: count,
              generate_row: 1,
              update_id : update_id
            }

            $.ajax({
                type: "POST",
                data : params,
                url: "/user/orders/basket/index.php",
                //url: "/bitrix/templates/.default/helpers/ajax/main_basket.php",
                success:function(result){
                    //$('tr.change_row').replaceWith(result);
                    $('#main-basket-wrap').replaceWith(result);
                    var total_count = $('#table_orders_list td.total-count').text();
                    var total_price = $('#table_orders_list td.total-price-val em').text();

                    $('#basket-line strong:first').text(total_count);
                    $('#basket-line strong:last').text(total_price+' р.');

                }
            });

            $('#art-list').hide();
       });

       // Обновление цветов в основной корзине
       $('#table_orders_list div.color-list li').live('click', function(){
            var params = {
                color_id : $(this).attr('rel'),
                size_id : $(this).parents('tr').find('div.size-val').attr('rel'),
                item_id : $(this).parents('tr').find('div.art-name').attr('rel'),
                art: $(this).parents('tr').find('div.art-name span').text(),
                update_basket_item: 1
            }

             $.ajax({
                type: "POST",
                data : params,
                url: "/bitrix/templates/.default/helpers/ajax/main_basket.php",
                success:function(result){

                }
            });
       });

       // Обновление размера в основной корзине
       $('#table_orders_list div.sizes-list li').live('click', function(){
            var params = {
                size_id : $(this).attr('rel'),
                color_id : $(this).parents('tr').find('div.color-block').attr('rel'),
                item_id : $(this).parents('tr').find('div.art-name').attr('rel'),
                art: $(this).parents('tr').find('div.art-name span').text(),
                update_basket_item: 1
            }

             $.ajax({
                type: "POST",
                data : params,
                url: "/bitrix/templates/.default/helpers/ajax/main_basket.php",
                success:function(result){

                }
            });
       });

       // Добавление нового артикула в основной корзине
       $('#new-order-btn').click(function(){

            // Отправляем общее количество для проверки типа цен
            var total_basket_count = $('#table_orders_list tfoot td.total-count').text();

            var params = {
                item_id : $('#art-list li:first').attr('rel'),
                new_row : 1,
                total_basket_count : total_basket_count
            }

             $.ajax({
                type: "POST",
                data : params,
                url: "/bitrix/templates/.default/helpers/ajax/main_basket.php",
                success:function(result){
                    $('#main-basket-wrap').html(result);
                    recalcMainBasket();

                }
            });


       });

       //Открытие списков в корзине
       $('#table_orders_list td.color i.ico, #table_orders_list td.size i.ico').live('click', function(){
            var parent_td = $(this).parents('td');
            var c = $(this).offset();
            var p = $('#table_orders_list').offset();
            var listWidth = $(parent_td).find('div.list').width();
            var list = $(parent_td).find('div.list');
            var cssDisplay;
            if($(list).css('display') == 'none'){
                cssDisplay = "block";
                $(list).addClass('display');
            }

            if($(list).css('display') == 'block'){
                cssDisplay = "none";
                $(list).removeClass('display');
            }

            var cssProps = {
                "display" : cssDisplay,
                "left" : (c.left - p.left) - listWidth + 20,
                "top" : c.top - p.top - 4
            }

            $(parent_td).find('div.list').css(cssProps);
       });

       // Обновление при изменении количества
       $('#table_orders_list td.count input').live('change', function(){

           var params = {
                size_id :  $(this).parents('tr').find('div.size-val').attr('rel'),
                color_id : $(this).parents('tr').find('div.color-block').attr('rel'),
                item_id :  $(this).parents('tr').find('div.art-name').attr('rel'),
                art: $(this).parents('tr').find('div.art-name span').text(),
                count : $(this).val(),
                update_count: 1,
                generate_row: 1
           }


           setTimeout(function(){
                $.ajax({
                type: "POST",
                data : params,
                url: "/user/orders/basket/index.php",
                //url: "/bitrix/templates/.default/helpers/ajax/main_basket.php",
                success:function(result){
                    $('tr.change_row').replaceWith(result);
                    $('#main-basket-wrap').replaceWith(result);
                    var total_count = $('#table_orders_list td.total-count').text();
                    var total_price = $('#table_orders_list td.total-price-val em').text();

                    $('#basket-line strong:first').text(total_count);
                    $('#basket-line strong:last').text(total_price+' р.');

                }
            });
           }, 1500);

       });

       var sub_lenght = $('#submenu div.menu-item').length;

       if(sub_lenght > 5){

           $('#content div.bg-top').addClass('bg-top2');
           $('#content div.bg-top').removeClass('bg-top');
       }

       $('a.print').click(function(){
            window.print();
            return false;
       });

       $('#mainmenu a').mouseover(function(){
           var i = $('#mainmenu a').index(this);
           if(i < 3){
               $('div.section').removeClass('show').removeClass('show-section').addClass('hide-section');
			   $('#submenu-wrap div.section').hide();
               $('div.hide-menu').show();
               $('#submenu-wrap div.section-'+(i+1)).show().removeClass('hide-section').addClass('show-section');
           }
		    if(i == 3){
               $('div.section').removeClass('show').removeClass('show-section').addClass('hide-section');
			   $('#submenu-wrap div.section').hide();
               $('div.hide-menu').show();
               $('#submenu-wrap div.section-' + (i+47)).show().removeClass('hide-section').addClass('show-section');
           }
		   if(i > 3){
               $('div.section').removeClass('show').removeClass('show-section').addClass('hide-section');
			   $('#submenu-wrap div.section').hide();
               $('div.hide-menu').show();
               $('#submenu-wrap div.section-'+i).show().removeClass('hide-section').addClass('show-section');
           }
       });

       $('#content, #header').mouseover(function(){
            $('div.hide-menu').hide();
            $('div.show').removeClass('show');
            $('div.section').removeClass('show-section').addClass('hide-section');
       });

       $('span.adress-print').live('click', function(){
           window.print();
       })

       $('div.material div').hover(function(){
           $(this).addClass('hover');
       },
       function(){
           $(this).removeClass('hover');
       });



       // Reg forms
       $('#reg-controls a').click(function(){
           $('#reg-controls a').removeClass('pl-active');
           $(this).addClass('pl-active');

           if($(this).hasClass('fiz')){
               $('#reg-fiz').removeClass('hidden');
               $('#reg-ur').addClass('hidden');
           }
           else{
               $('#reg-fiz').addClass('hidden');
               $('#reg-ur').removeClass('hidden');
           }
           return false;
       });

       // Order disabled
       $('#agree').attr('checked', '');
       $('#agree').live('click', function(){

           if($('#go-order-link').hasClass('disabled')){
               $('#go-order-link').removeClass('disabled').addClass('enabled');
               $('#go-order-link img').attr('src', '/bitrix/templates/main/images/confirm-order-btn.png');
           }
           else{
               $('#go-order-link').addClass('disabled').removeClass('enabled');
               $('#go-order-link img').attr('src', '/bitrix/templates/main/images/confirm-order-btn-disabled.png');

           }
       });

       $('#main-basket-wrap a.disabled').live('click', function(){
                return false;
       });


       $('#main-basket-wrap div.check a.pseudo-link').live('click', function(){
           var w_coords = $('#wrap').offset();
           var coords = $(this).offset();
           var params = {
               'ajax' : 'y'
           }
            $.ajax({
                type: "POST",
                data : params,
                url: "/purchase-terms/e-commerce/index.php",
                success:function(result){
                    var template = '<div style="left: '+(w_coords.left - 150)+'px;top: '+(w_coords.top + 50)+'px;" id="material-win" class="d-shadow agree-win"><div class="d-shadow-wrap"><div class="body"><div class="close-cross"></div><div class="content">'+result+'</div></div><div class="d-sh-cn d-sh-tl"></div><div class="d-sh-cn d-sh-tr"></div></div><div class="d-sh-cn d-sh-bl"></div><div class="d-sh-cn d-sh-br"></div></div>';
                    $('#wrap').append(template);
                }
            });

            return false;
       });
       
       
       // Print list selector
       $('.print-item-selector ul li').live('click', function(){
       		var side = $(this).attr('rel');
       		$(this).parent().children().removeClass('selected');		
       		$(this).addClass('selected');
       		$(this).parent().parent().parent().children(':first-child').children('div').hide();
       		$(this).parent().parent().parent().children(':first-child').children('div[rel='+side+']').show();
       });


      //* Prints order *//
	
	  //Show
	  $('.print-item-img').click(function(){
	  	$(this).next().next().click();
	  })		  
	  
	  $('.buy-print').click(function(){
			$('.print-item-detail').hide();
	  		block = $(this).attr('rel');
	  		$('.print-item-detail[rel='+block+']').show();
	  		var position = $(this).position();
	  		$('.print-item-detail').css({top: position.top - 100});
	  		$('.print-item-detail').css({left: position.left});

 		    $('span.print-item-order-params-header-color-header').next().trigger("click");
		    $('.print-item-order-size-selector').trigger("change");

	  		return false;			
	  });

	  //Close
	   $('.close-print-order').click(function(){
			$('.print-item-detail').hide();
	   });


	  //Color-order-selector
	   $('.print-item-order-color-selector div').click(function(){
			$('.print-item-order-color-selector div').html('<img src="/bitrix/templates/main/images/prints_color.png" />');
			$(this).html('<img src="/bitrix/templates/main/images/prints_color_selected.png" />');
	   		block = $(this).attr('rel');
	   		$('.print-item-order-decription-color[rel='+block+']').html($(this).attr('color_name') +' ('+$(this).attr('color_num')+')');
	   		$('form[rel='+block+'] input[name=color]').val($(this).attr('color_id'));
	   });
	  
	   $('select.print-item-order-size-selector').change(function() {
			block = $(this).attr('rel');
	   		$('form[rel='+block+'] input[name=size]').val($(this).val());
			$("select.print-item-order-size-selector option:selected").each(function () {
                $('.print-item-order-decription-size[rel='+block+']').html( $(this).text() );
            });
	   });
	  
	  //Submit
	   $('.send-print-order').click(function(){
	   		block = $(this).attr('rel');
	   		$('form[rel='+block+']').submit();
	   });
	  
	  

	  //Send
/*	  $('#send-print-order').click(function(){
			if ($('#prn-ord-phone').val() == '') {
			    $('#prn-ord-phone').addClass('error');
			} else {
	
				var params = {
					'name' : $('#prn-ord-name').val(),
					'email': $('#prn-ord-email').val(),
					'phone': $('#prn-ord-phone').val(),
					'message': $('#prn-ord-tshirts-name').val() +". Колличество: "+ $('#prn-ord-qty').val() +". Город: "+ $('#prn-ord-city').val() +". Размер: "+ $('#prn-ord-size').val() +". Комментарий: "+ $('#prn-ord-message').val()
				}
	
				$.ajax({
					type: "POST",
					data : params,
					url: "/bitrix/templates/.default/helpers/ajax/feedback.php",
					success:function(result){
						$('[rel=form]').hide();
					}
				});
			}
	
		});
*/		
		
      $('#prn-ord-phone').click(function(){
          $(this).removeClass('error');
      });
      
      //* Vacancies *//
      $('span.job-item-name').click(function(){
      		$(this).next().toggle("fast");    
			$(this).toggleClass("selected");
      })
      
      //* News *//
      $('div.news-year-item').click(function(){
      		$(this).next().toggle("fast");
      })
      
      //* Awards *//
      $('p.award-selector a').click(function(){
      		$('p.award-selector a').removeClass('selected');
      		$(this).addClass('selected');
      		sec = $(this).attr('href');
      		if(sec == 'all'){
      			$('#awards-container div.review-item').show();
      		} else {
      			$('#awards-container div.review-item').hide();
      			$('#awards-container div[rel='+sec+']').show();
      		}
      		return false;
      })
      
      
		
});
