function captchaReload(url)
{
	$.getJSON(
		url,
        function(data)
        {
            $('#captcha_id').prev().prev().prev().attr('src', '/images/captcha/' + data.captcha_id + '.png');
            $('#captcha_id').val(data.captcha_id);
        }
	);
}

function clearInputValue( id, value)
{
    if( $('#' + id).val() == value) $('#' + id).val('');
}

function restoreInputValue( id , value)
{
    if( $('#' + id).val()== '') $('#' + id).val( value);
}

function swap(off, on)
{
    $( "#" + off).hide();
    $( "#" + on).show();
}

function showProductMenu()
{
    pm = document.getElementById("productMenu");
    if( pm.style.display == "none")
    {
        $( "#productMenu").show();
    }
    else
    {
        $( "#productMenu").hide();
    }
}

function showSubMenu( id)
{
    pm = document.getElementById(id);

    if( pm.style.display == "none" || pm.style.display == "")
    {
        $( "#" + id).show();
    }
    else
    {
        $( "#" + id).hide();
    }
}

function sendComplaint( params)
{
    $.getJSON("/complaint/new"+ params,
        function(data){
            alert( data.message);
        });
}

/* Желания список */

function goToPage( page)
{
    $('#page').val( page);
    var qString = $("#selectionForm").formSerialize();
    window.location = '?' + qString + '&paging=1';
}

function changePageCount()
{
    $('#page').val( 0);
    var qString = $("#selectionForm").formSerialize();
    window.location = '?' + qString + '&paging=1';
}

function showWishDetail( id)
{
    if( $('#w' + id + 'Detail').css("display") == "none")
    {
        $('#w' + id + 'Detail').show();
        $('#w' + id + 'DetailLink').html('<img src="/images/op_1.gif" alt="" />');
    }
    else
    {
        $('#w' + id + 'Detail').hide(); //load("/catalog/selection/load-wish-detail?id=" + id);
        $('#w' + id + 'DetailLink').html('<img src="/images/op_2.gif" alt="" />');
    }
}

function addDelWish( id)
{
    $('#w' + id).hide();
    $('#w' + id + 'Shadow').hide();
    $('#w' + id + 'Response').hide();
    
    $('#w' + id+ 'Input').attr( 'disabled', 'true' );
    $('#w' + id + 'Hidden').show();

    $.getJSON("/catalog/selection/add-del-wish?wishId="+ id,
        function(data){
            if( data.ret)
                {
                    $('#wishPrice').val( parseInt( $('#wishPrice').val()) - parseInt( $('#w' + id + 'Price').text()));
                    $('#wishCount').val( parseInt( $('#wishCount').val()) - 1);

                    setOrderSumString();

                    if( $('#wishCount').val() == 0)
                    {
                        $('#nextStepButton').removeClass('submit_4');
                        $('#nextStepButton').html('<a>Желания не выбраны</a>');
                    }
                };
        });


}

function removeDelWish( id)
{
    $('#w' + id).show();
    $('#w' + id + 'Shadow').show();
    $('#w' + id + 'Response').show();

    $('#w' + id+ 'Input').attr( 'disabled', '' );
    $('#w' + id + 'Hidden').hide();
    $.getJSON("/catalog/selection/remove-del-wish?wishId="+ id,
        function(data){
            if( data.ret)
                {
                    if( $('#wishCount').val() == 0)
                    {
                        $('#nextStepButton').addClass('submit_4');
                        $('#nextStepButton').html('<a href="javascript:void(0)" onclick="goToResponseChoice()" >Перейти к назначению отклика</a>');
                    }

                    $('#wishPrice').val( parseInt( $('#wishPrice').val()) + parseInt( $('#w' + id + 'Price').text()));
                    $('#wishCount').val( parseInt( $('#wishCount').val()) + 1);

                    setOrderSumString();
                };
        });
}

function setOrderSumString()
{
    //$('#orderSumString').text('Выбрано '+ $('#wishCount').val() +' желаний на сумму ' + $('#wishPrice').val() + ' руб.');
    $('#orderWishCountId').text( $('#wishCount').val());
    $('#orderPriceId').text( $('#wishPrice').val());

}

function hideWishImages()
{
    $('#showImages').val(0);
    $('td.wishImageBlock').hide();

    $('#showImagesC').addClass('activ');
    $('#hideImagesC').removeClass('activ');
}

function showWishImages()
{
    $('#showImages').val(1);
    $('td.wishImageBlock').show();

    $('#showImagesC').removeClass('activ');
    $('#hideImagesC').addClass('activ');
    
    
}

/* Форма выборки */

function saveSelection( type)
{
   var qString = $("#selectionForm").formSerialize();

    if( type == 1)
    {
        q = "/catalog/selection/save-selection-from-session?"+ qString;
    }
    else
    {
        q = "/catalog/selection/save-selection?"+ qString;
    }

    //alert( q);
    
    $.getJSON( q,
        function(data){
            if( data.errorCode)
            {
                alert('Для сохранения выборки просим зарегистрироваться');
            }
            else
            {
                $('#id').val( data.id);
                //alert( data.name);
                $('#selectionName').val( data.name);
            }

            showSelectionNameText();
        });
    
}

function saveSelectionAndSubscribe()
{
    var qString = $("#selectionForm").formSerialize();
    window.location = '/catalog/selection/save-selection?subscribe=1&' + qString;

}

function showSelectionNameInput( type)
{
    if( !type) type = 0;

    newHtml =
        '<input type="text" name="selectionNameNew" '+
            ' id="selectionNameNew" value="" /><br/>';

    newHtml += '<input type="button" name="cancel" '+
            '   value="отмена" onclick="showSelectionNameText()" /> ' +
        '<input type="button" name="save" '+
            '   value="Сохранить" onclick="saveSelection('+type+')" /><div class="clear"></div> ';

    $("#selectionNameBlock").html( newHtml);

    if( $( "#id").val() > 0)
    {
        $( "#selectionNameNew").val( $( "#selectionName").val());
        
    }
    else
    {
        $( "#selectionNameNew").val('Новая выборка');
    }
}

function showSelectionNameText()
{
    $("#selectionNameBlock").html('<h2></h2><input type="button" onclick="showSelectionNameInput()" class="submit_1" name="" value="Сохранить" /><div class="clear"></div>');
    if( $( "#id").val() > 0)
    {
        $("#selectionNameBlock h2").text( $( "#selectionName").val());
        $("#selectionNameBlock").append("Выборка сохранена");
    }
    else
    {
        $("#selectionNameBlock h2").text('Новая выборка');
    }
}

function goToResponseChoice()
{
    var qString = $("#selectionForm").formSerialize();
    // check if user logged in
    if (document.getElementById("info_user_01")) {
	    window.location = '/catalog/response/?next=1&fromSelection=1&' + qString;
	  } else {
	  	loginWindow();
	  }
}

function goToOrder()
{
   var qString = $("#selectionForm").formSerialize();
    window.location = '/catalog/order/?next=1&' + qString;
}

function orderSelection( orderBy)
{
    $('#search').val(1);
    $('#orderBy').val( orderBy);
    var qString = $("#selectionForm").formSerialize();
    window.location = '?' + qString;
}

function toggleBlock( id)
{
    if( $( "#" + id).css('display') == 'block')
    {
        $( "#" + id + 'Label').addClass( 'zag_bl_z');
    }
    else
    {
        $( "#" + id + 'Label').removeClass( 'zag_bl_z');
    }
    $( "#" + id).toggle();

}

function openCategoryWindow( url)
{
    $.nyroModalManual({
      url: url,
      width: 900,
      height: 560
    });
}

function loadSubCategoryList( tcid)
{
    $.getJSON( "/catalog/selection/w-category-list/tcid/" + tcid,
        function(data){
            $('.activ_p_a').removeClass('activ_p_a');
            $('.table_ru .td_2').remove();
            $('.table_ru .td_3').remove();
            $('.table_ru .td_1').after( data.html);
            $('#topCat'+tcid).parent().addClass('activ_p_a');
        });
}

function selectCategory( cid)
{
    $("#cid").val( cid);
    $('#changeCategory').val(1);
    $('#search').val(1);
    $("#selectionForm").submit();
    $.nyroModalRemove();

}

function reloadResponsePage()
{
    var qString = $("#selectionForm").formSerialize();
    window.location = '/catalog/response/?' + qString;
}

function setResponse( id, wishId)
{
    window.location = '/catalog/response/set-response?responseId='+id + '&wishId=' + wishId;
}

function openSelectResponseWindow( wishId)
{
    $.nyroModalManual({
      url: '/catalog/response/show-response-list-w?wishId='+parseInt(wishId),
      zIndexStart: 1000
    });

}

function openNewResponseWindow( wishId)
{
    $.nyroModalManual({
      url: '/catalog/response/show-response-form-w?wishId='+parseInt(wishId),
      width: 960,
      zIndexStart: 1000,
      modal: true

    });

}

function openNewDemandWindow()
{
	$.nyroModalManual({
		url: '/partners/show-demand-form',
		width: 670,
		zIndexStart: 1000,
		modal: true
		
	});
}

function nextRandomWishes( num)
{
    $('#randomWishBlock').load('/index/next-wishes?nextWishNum=' + num);
}

function saveSelectionFilter( userId)
{
    var qString = $("#selectionForm").formSerialize();
    window.location = '/personal/'+userId + '/selection/save-filter/?' + qString;
}

function setNotifyOn( id)
{
    $('#' + id).val( 1);
    $('#' + id + 'C').html('<span class="vk_color">Включена</span> | <a href="javascript:setNotifyOff( \''+id+'\')" >Отключить</a>');

    if( id == "notifyFlag")
    {
        $('#email').attr("disabled", false);
        $('#nt1').attr("disabled", false);
        $('#nt2').attr("disabled", false);
        $('#notifyWishCount').attr("disabled", false);
    }
    else
    {
        $('#responseId').attr("disabled", false);
        $('#newWishCount').attr("disabled", false);
        $('#dayIntervalFlag').attr("disabled", false);
        $('#dayInterval').attr("disabled", false);
        $('#emailNotifyFlag').attr("disabled", false);
        $('#emailAutobuy').attr("disabled", false);

    }


}

function setNotifyOff( id)
{
    $('#' + id).val( 0);
    $('#' + id + 'C').html('<span>Отключена</span> | <a href="javascript:setNotifyOn( \''+id+'\')">Включить</a>');

    if( id == "notifyFlag")
    {
        $('#email').attr("disabled", true);
        $('#nt1').attr("disabled", true);
        $('#nt2').attr("disabled", true);
        $('#notifyWishCount').attr("disabled", true);
    }
    else
    {
        $('#responseId').attr("disabled", true);
        $('#newWishCount').attr("disabled", true);
        $('#dayIntervalFlag').attr("disabled", true);
        $('#dayInterval').attr("disabled", true);
        $('#emailNotifyFlag').attr("disabled", true);
        $('#emailAutobuy').attr("disabled", true);
    }
}

function resendRegEmail( newUserId)
{
    $.getJSON("/reg/resend-reg-email?newUserId="+ newUserId,
        function(data){
            if( data.errorCode > 0)
            {
                alert('Ошибка:' + data.errorMessage);
            }
            else
            {
                alert('Письмо о подтверждении регистрации отправлено повторно');
            }
        });
}


function interactResponse( id)
{
    if( id == "phoneCode" || id == "phone")
    {
        $('#phoneView').text('+7 ' + $('#phoneCode').val() + ' ' + $('#phone').val());
    }
    else
    {
        $('#' + id + 'View').text( $('#' + id).val());
    }


    if( id == "comment")
    {
        //$('#' + id + 'View').html( nl2br( $('#' + id).val()));
        //if( $('#' + id).val().length >= 200) $('#' + id).val( $('#' + id).val().substring( 0, 200));
        comment = $('#' + id).val();
        comment = comment.replace(/\n/g, "");
        
        $('#commentStrLen').text( comment.length + '/200');
        
    }
}


function updateNewWishStat( selectionId, userId)
{
    $.getJSON("/personal/"+userId+ "/selection/update-new-wish-stat?selectionId="+ selectionId,
        function(data){
            if( data.error == 0)
            {
                $('#newWishCount' + selectionId).text( data.wishCount);
                $('#newWishSum' + selectionId).text( data.wishSum);
            }
            else
            {
                alert('Ошибка');
            }
        });
}

var popSearchTimer;

function ajaxSearch( height)
{
    if( height == '-600px' && $('#w').val().length < 3) return;

    $('#popSearchResult').html('<img src="/images/ajax-loader.gif" />');
    $('#popSearchResult').css('margin-top', height);
    $('#popSearchResult').show();

    clearTimeout( popSearchTimer);

    var qString = $("#selectionForm").formSerialize();

    $.getJSON("/catalog/selection/ajax-search/?"+ qString,
        function(data)
        {
            $('#popSearchResult').html('Найдено<br />'+ data.wishCount + ' ' + data.word + ' <a href="javascript:void(0)" id="ajaxSearchLink">Показать</a>');

            popSearchTimer = window.setTimeout("$('#popSearchResult').hide();", 5000);
            
            $('#ajaxSearchLink').click(function()
            {
                 $('#search').val(1);
                 $('#selectionForm').submit();
            });
        });
}


      function nl2br(text){
      text = escape(text);
      if(text.indexOf('%0D%0A') > -1){
      re_nlchar = /%0D%0A/g ;
      }else if(text.indexOf('%0A') > -1){
      re_nlchar = /%0A/g ;
      }else if(text.indexOf('%0D') > -1){
      re_nlchar = /%0D/g ;
      }
      return unescape( text.replace(re_nlchar,'<br />') );
      }

/*
 * Функции редактирования названия выборки для личного кабинета
 */
function editSelectionName()
{
    $('#selectionName').hide();
    $('#editSelectionNameLink').hide();
    $('#selectionNameNew').val( $('#selectionName').text());
    $('#selectionNameEditBlock').show();


}

function saveSelectionName( userId, id)
{
    $.getJSON("/personal/" + userId + "/selection/save-selection-name/?id="+ id+ "&name=" + $('#selectionNameNew').val(),
        function(data)
        {
            if (data.error == 0)
            {
                $('#selectionName').text( $('#selectionNameNew').val());
                $('#selectionName').show();
                $('#editSelectionNameLink').show();
                $('#selectionNameEditBlock').hide();
            }
            if( data.error == 1)
            {
                alert( data.errorMsg);
            }
            
        });
}



//заказ желаний
function addWishToOrder( id)
{
    $.getJSON("/catalog/basket/add-wish-to-order?wishId="+ id,
        function(data){
            if( data.ret)
                {
                    if( $('#wishCount').val() == 0)
                    {
                        $('#nextStepButton').addClass('submit_4');
                        $('#nextStepButton').html('<a href="javascript:void(0)" onclick="goToResponseChoice()" >Перейти к назначению отклика</a>');
                    }

                    $('#wishPrice').val( parseInt( $('#wishPrice').val()) + parseInt( $('#w' + id + 'Price').text()));
                    $('#wishCount').val( parseInt( $('#wishCount').val()) + 1);

                    setOrderSumString();

                    $('#w' + id).addClass('gelanie_bl_green');
                    $('#w' + id + 'CheckIcon').show();
                    $('#orderLink' + id).html('<a href="javascript:removeWishFromOrder( '+id+')"><img src="/images/minus.gif" alt="" /></a><a href="javascript:removeWishFromOrder( '+id+')">УДАЛИТЬ из заказа</a>');
                };
        });


}

function removeWishFromOrder( id)
{
    $.getJSON("/catalog/basket/remove-wish-from-order?wishId="+ id,
        function(data){
            if( data.ret)
                {
                    $('#wishPrice').val( parseInt( $('#wishPrice').val()) - parseInt( $('#w' + id + 'Price').text()));
                    $('#wishCount').val( parseInt( $('#wishCount').val()) - 1);

                    setOrderSumString();

                    if( $('#wishCount').val() == 0)
                    {
                        $('#nextStepButton').removeClass('submit_4');
                        $('#nextStepButton').html('<a>Желания не выбраны</a>');
                    }

                    $('#w' + id).removeClass('gelanie_bl_green');
                    $('#w' + id + 'CheckIcon').hide();
                    $('#orderLink' + id).html('<a href="javascript:addWishToOrder( '+id+')"><img src="/images/plus.gif" alt="" /></a><a href="javascript:addWishToOrder( '+id+')">ДОБАВИТЬ в заказ</a>');
                };
        });
}

function selectAllWishes()
{
     var qString = $("#selectionForm").formSerialize();
    $.getJSON("/catalog/basket/add-all-to-order/?"+ qString,
        function(data){
            if( data.ret && data.wishCount>0)
                {
                    $('.gelanie_bl').addClass('gelanie_bl_green');
                    $('.checkIcon').show();
                    $('.iskluchit').each( function( index)
                    {
                        id = $(this).attr('id').substring( 9);
                        $(this).html('<a href="javascript:removeWishFromOrder( '+id+')"><img src="/images/minus.gif" alt="" /></a><a href="javascript:removeWishFromOrder( '+id+')">УДАЛИТЬ из заказа</a>');
                    });

                    if( $('#wishCount').val() == 0)
                    {
                        $('#nextStepButton').addClass('submit_4');
                        $('#nextStepButton').html('<a href="javascript:void(0)" onclick="goToResponseChoice()" >Перейти к назначению отклика</a>');
                    }

                    $('#wishPrice').val( data.wishPrice);
                    $('#wishCount').val( data.wishCount);

                    setOrderSumString();

                }
                else
                {
                    alert('Желания не выбраны. Измените параметры фильтра');
                }
        });
}

function unselectAllWishes()
{
     var qString = $("#selectionForm").formSerialize();
    $.getJSON("/catalog/basket/remove-all-from-order/?"+ qString,
        function(data){
            if( data.ret)
                {
                    $('.gelanie_bl').removeClass('gelanie_bl_green');
                    $('.checkIcon').hide();
                    $('.iskluchit').each( function( index)
                    {
                        id = $(this).attr('id').substring( 9);
                        $(this).html('<a href="javascript:addWishToOrder( '+id+')"><img src="/images/plus.gif" alt="" /></a><a href="javascript:addWishToOrder( '+id+')">ДОБАВИТЬ в заказ</a>');
                    });

                    $('#wishPrice').val( 0);
                    $('#wishCount').val( 0);

                    setOrderSumString();

                    $('#nextStepButton').removeClass('submit_4');
                    $('#nextStepButton').html('<a>Желания не выбраны</a>');
                }
        });
}


function loginWindow()
{
    $.nyroModalManual({
      url: '/auth/login-form-small',
      width: 670,
      zIndexStart: 1000

    });

    return false;

}

function regWindow()
{
    $.nyroModalManual({
      url: '/reg/small',
      width: 670,
      zIndexStart: 1000

    });

    return false;
}

function remindWindow()
{
    $.nyroModalManual({
      url: '/auth/forget-small',
      width: 670,
      zIndexStart: 1000

    });

    

    return false;
}


