$(document).ready(function(){

    $(".specialOffersText span.image").each(function(){
        if ($(this).height() > $(this).parent().next().height() )
        {
            //$(this).parent().next().css('height',$(this).height()+'px');
        }
        var el= $(this).parent().parent().height()/2 -$(this).height()/2;
        $(this).css('margin-top','' + el  + 'px');
    });

    $(".topperBlockImg img").each(function()
    {
        if ($(this).height() > $(this).parent().next().height() )
        {
            $(this).parent().next().css('height',$(this).height()+'px').css('padding-bottom','40px');
        }
        var el=$(this).parent().parent().height()/2+20 -$(this).height()/2;
        $(this).css('margin-top','' + el  + 'px');
    });

    $.datepicker.setDefaults($.datepicker.regional['ru']);
    $("#start_date").datepicker();
    $("#exp_date").datepicker();
    
    if ($('#city').val()==1) {
        $('#area').attr('disabled', 'disabled');
    }

    if (!$(".copyToBuff").length == 0)
    {
        var clip = null;

        clip = new ZeroClipboard.Client();
        clip.setHandCursor( true );

        $('div.copyToBuff').mouseover(function() {

            var coupon_id = $(this).attr('rel');

            clip.setText( $(this).find('b').text() );

            if (clip.div) {
                clip.receiveEvent('mouseout', null);
                clip.reposition(this);
            } else {
                clip.glue(this);
            }

            clip.receiveEvent('mouseover', null);
            clip.addEventListener('complete', function() {
                top.location.href='/store/go_without_affiliate/'+coupon_id;
            });

        });
    }

    $(".copyToBuff span").mouseout(function(){
        $(".hover").removeClass('hover');
    });
        
    $('#city,#area').change(function(){
        if ($(this).attr('id') == 'city') {
            $("#location_form").submit(); 
            return false;
        }
        
        $("#location_form").submit(); 
        
    });

    $("#search_form").click(function(){
        $(this).val('');
        return false;
    });
    
    $("span.helped").click(function(){
        var id = $(this).attr('id');
        $.ajax({
            url: '/coupons/coupon_helped/' + id,
            success: function() {
                $('span.notHelped#'+id).hide();
            }
        });
    });
    
    $("span.notHelped").click(function(){
        var id = $(this).attr('id');
        $.ajax({
            url: '/coupons/coupon_not_helped/' + id,
            success: function() {
                $('span.helped#'+id).hide();
            }
        });
    });
    
    $("a.open_comments").click(function(e){
        e.preventDefault();
        if ($(this).attr('href') == '#no'){
            return false;
        }
        var coupon = $(this).attr('rel');
        $('div#comments_'+coupon).show();
    });
    
    $("span.close_comments").click(function(){
        $(this).parent('div').parent('div').hide();
    });

    function adjustCity()
    {
        var city_id = $('#city_ch').val();
        var tmpSelect = $('#area_ch');
        if ($('#city_ch').attr('class') == 'noactive') {
            $('#city_ch').attr('class','active');
            return false;    
        }
        if (city_id == 1) {
            $('#store_address').parent().hide();
            $('label[for="store_address"]').parent().hide();
        } else {
            $('#store_address').parent().show();
            $('label[for="store_address"]').parent().show();
        }
        
        $.ajax({
            url: '/location/getcityareas/'+city_id,
            dataType: "text",
            success: function(data) {
                json = eval("(" + data + ")");
                $('#area_ch').fillSelect(json).attr('disabled','');
            }
        });
        
        $.ajax({
            url: '/store/getstores/'+city_id,
            dataType: 'json',
            success: function(data) {
                $('#store_id').fillSelect(data).attr('disabled','');
            }
        });
    }
    
    $('#city_ch').change(function(){
        adjustCity();
    });

    $('#city_ch_manager').change(function(){
        var city_id = $('#city_ch_manager').val();
        $.ajax({
            url: '/store/getstoresaddress/'+city_id,
            dataType: 'json',
            success: function(data) {
                $('#store_id').fillSelect(data).attr('disabled','');
            }
        });
    });

    $('form.addCouponForm #store_id').change(function(){
        var store_id = $(this).val();
        $.ajax({
            url: '/store/getinfo/'+store_id,
            dataType: 'json',
            success: function(data) {
                $('#store_url').attr('readonly','readonly').val(data.url);
                $('#store_email').attr('readonly','readonly').val(data.email);
                $('#store_address').attr('readonly','readonly').val(data.address);
                $('#store_phone').attr('readonly','readonly').val(data.phone);
            }
        });
    });

    $('form.addCouponForm #store_name').keydown(function(){
        if ($(this).val() == '') {
            $('#store_address').attr('readonly','').val('');
            $('#store_phone').attr('readonly','').val('');
            $('#store_url').attr('readonly','').val('');
        }
    });

    $('#link_add_store').click(function(e){
        e.preventDefault();
        $('#store_add').show();
        $('#store_select').hide();
        $('#store_id').val(0);
    });
    
    $(".userRateTable tr:even").addClass('colored');
    $(".tableOfUsers tr:even").addClass('even');
    $(".tableOfStoresScroller table tr:even").addClass('even');

    /*прокрутка FAQ*/

    $(".listOfQuestionLinks a").click (
        function(){
            $('body').scrollTo($(this).attr('href'), 800);
            return false;
        });

    

    $('.carouselWrap').jCarouselLite(
    {
        btnPrev: '#btnPrev',
        btnNext: '#btnNext',
        visible: 1,
        speed: 500
    });

    /*открытие\скрытие комментариев по клику на "комментарии"*/


    $("span.commentry").click (
        function(){

            var blockcoment = $(this).parent().parent().next();

            if ($(this).hasClass('noCommentaries'))
            {

                /*
                 динамическая подрузка попапа
             */

                var btnlink = $(this).attr("value");
                $('div.main').css('z-index', 200);

                try
                {
                    $.ajax({
                        type: "post",
                        url: btnlink ,
                        success: function(data)
                        {
                            popupCenter();
                            $("#addCommentary").append(data);
                            $("#addCommentary").css('display','block');
                            submitsender();
                        }
                    });
                }
                catch(e)
                {
                    alert("Ошибка. Попробуйте еще раз.");
                }

            }
            else
            {
                if (blockcoment.css("display")=="none")
                {
                    blockcoment.css('display','block');
                }
                else
                {
                    blockcoment.css('display','none');
                }
            }

        });


    $("span.addAComment").click (
        function(){

            /*
                 динамическая подрузка попапа
         */

            var btnlink = $(this).attr("value");
            $('div.main').css('z-index', 200);

            try
            {
                $.ajax({
                    type: "post",
                    url: btnlink ,
                    success: function(data)
                    {
                        popupCenter();
                        $("#addCommentary").append(data);
                        $("#addCommentary").css('display','block');
                        submitsender();
                    }
                });
            }
            catch(e)
            {
                alert("Ошибка. Попробуйте еще раз.");
            }
        });

    /*закрытие комментариев по кнопке "закрыть"*/


    $(".Actionsblock span").eq(0).click (
        function(){

            $(this).parent().parent().css('display','none');

        });


    /*закрытие попапа по кнопке "закрыть"*/

    $("#addCommentary .closeButton").click (
        function(){

            $(this).parent().find('form').remove();
            $(this).parent().css('display','none');
            $('div.main').css('z-index', 0);

        });

    $('form.validateSorting input#sort').click(function(){
        sort_coupons();
    });

    $('#valSortCity').change(function(){
        var city_id = $('#valSortCity').val();
        $.ajax({
            url: '/store/getstores/'+city_id,
            dataType: 'json',
            success: function(data) {
                $('#valSortStoreName').fillSelect(data).attr('disabled','');
                $('#valSortStoreName option:first-child').attr('selected', 'selected');
                $('#valSortId option').remove();
                $('#valSortId').append($("<option></option>").attr("value",0).attr('selected', 'selected'));
            }
        });
    });

    $('#valSortStoreName').change(function(){
        var store_id = $('#valSortStoreName').val();
        $.ajax({
            url: '/coupons/getcoupons/'+store_id,
            dataType: 'json',
            success: function(data) {
                $('#valSortId').fillSelect(data).attr('disabled','');
            }
        });
    });

});

function sort_coupons()
{
    var city_id = $('#valSortCity').val().toString();
    var store_id = $('#valSortStoreName').val().toString();
    var coupons_id = $('#valSortId').val().toString();

    var sort = {
        'city_id': city_id,
        'store_id': store_id,
        'coupon_id': coupons_id
    };
    $.ajax({
        url: '/coupons/getcouponssort/',
        type: 'post',
        data: sort,
        dataType: 'json',
        success: function(coupons) {
            $('.listOfCheckingSale li').remove();
            var htmlAppend = '';
            var htmlAppendId = '';
            if (coupons.length == 0) {
                $('.listOfCheckingSale li').remove();
                var htmlAppend = '<li><h3>Все скидки находятся на проверке у администратора</h3></li>';
                $('.listOfCheckingSale').append(htmlAppend);
            } else {
                jQuery.each(coupons, function() {
                    var coupon = this;
                    var hostname = window.location.hostname;
                    var target = '';
                    var href1 =  '';
                    var href2 =  'http://' +hostname + '/coupons/verification/' + coupon['coupon_id'];
                    htmlAppendId += '<option value="' + coupon['coupon_id'] +'">' + coupon['name'] + '</option>';
                    if (coupon['url']) {
                            href1 = 'http://' + hostname + 'store/go/' + coupon['coupon_id'];
                            target = 'target="_blank"';
                        } else if (coupon['store_url']) {
                            href1 = 'http://' + hostname + 'store/gostore/' + coupon['store_id'];
                            target = 'target="_blank"';
                        } else {
                            href1 = 'http://' + hostname + 'store/store/viewinfo/' + coupon['store_id'];
                            target = 'rel="superbox[iframe]"';
                        }
                    htmlAppend += '<li><h3><a href="' + href1 +'" ' + target + '>' + coupon['name'] + '</a></h3>'
                    + coupon['descr_short'] + '<a href="' + href2 +'" class="checkThisSale">Проверить</a></li>';
                });
                $('#valSortId option').remove();
                $('#valSortId').append(htmlAppendId);
                $('.listOfCheckingSale').append(htmlAppend);
            }
        },
        error: function(){
           $('.listOfCheckingSale li').remove();
           var htmlAppend = '<li><h3>Все скидки находятся на проверке у администратора</h3></li>';
           $('.listOfCheckingSale').append(htmlAppend);
        }
            
    });
}

function limitText(limitField, limitNum) {
    if (limitField.value.length > limitNum) {
        limitField.value = limitField.value.substring(0, limitNum);
    } 
}

function expand_description(coupon_id)
{
    $('#descr_short_'+coupon_id).hide();
    $('#descr_long_'+coupon_id).show();
    if ((jQuery.browser.msie) && (jQuery.browser.version == 8))
    {
        jQuery(".announceContWrap").css('display','block');
        jQuery(".announceContWrap").css('display','inline-block');
    }
    return false;
}

/*
    функция центрирования попапа с учётом скролла
     */

function popupCenter() {

    var	wsize = windowWorkSize(),                                               // размеры "рабочей области"
    testElem = $("#addCommentary"),                        // ложим наш блок в переменную
    testElemWid =  testElem.width(),                                    // ширина блока
    testElemHei =  testElem.height();

    leftPos = wsize[0]/2 - testElemWid/2 + "px";        // центрируем блок по горизонтали
    topPos = wsize[1]/2 - testElemHei/2 + (document.body.scrollTop || document.documentElement.scrollTop) + "px";    // центрируем блок по вертикали + скролл

    testElem.css('top',topPos );
    testElem.css('left',leftPos );


    // фунция определения "рабочего пространства"
    function windowWorkSize(){
        var wwSize = new Array();
        if (window.innerHeight !== undefined) wwSize= [window.innerWidth,window.innerHeight];    // для основных браузеров
        else
        {	// для "особо одарённых" (ИЕ6-8)
            wwSizeIE = (document.body.clientWidth) ? document.body : document.documentElement;
            wwSize= [wwSizeIE.clientWidth, wwSizeIE.clientHeight];
        }
        return wwSize;
    }
}

/*
    функция сабмита комментария
     */

function submitsender()
{

    $("#addCommentary form").die('submit').live('submit',
        function()
        {

            var str = $("#addCommentary form").serialize();

            try
            {
                $.ajax({
                    url: $("#addCommentary form").attr('action'),
                    data: str,
                    type: "post",
                    timeout: 5000,
                    success: function(data){

                        $("#addCommentary").find("form").remove();
                        $("#addCommentary").append(data);

                    /*
                    jQuery("#addCommentary form").remove();
                    jQuery("#addCommentary").append('<div id="temporary" style="padding: 50px 0; font-size:20px; text-align:center;">Спасибо за отзыв! Ваш комментарий будет опубликован после проверки администратором.</div>');

                    setTimeout(function() {
                        jQuery("#addCommentary").fadeOut(200);
                    }, 2000);

                    setTimeout(function() {
                        jQuery("#temporary").remove();
                    }, 2300);
                         */
                    }
                });
            }
            catch(e)
            {
                alert("При поиске произошла неизвестная ошибка. \n Попробуй еще раз через несколько минут.");
            }

            return false;
        });
}

(function($){
    // очищаем select
    $.fn.clearSelect = function() {
        return this.each(function(){
            if (this.tagName=='SELECT') {
                this.options.length = 0;
                $(this).attr('disabled','disabled');
            }
        });
    };
    // заполняем select
    $.fn.fillSelect = function(dataArray) {
        return this.clearSelect().each(function(){
            if (this.tagName=='SELECT') {
                var currentSelect = this;
                $.each(dataArray,function(index,data){
                    var option = new Option(data.text,data.value);
                    if ($.support.cssFloat) {
                        currentSelect.add(option,null);
                    } else {
                        currentSelect.add(option);
                    }
                });
            }
        });
    }
})(jQuery);

