function changeClickableItem(id) {
    if ($("li[id^='item-select-'] a.act").parent().attr('id').split('-')[2] != id) {
        $('.clickable').fadeOut('slow');
        $('.clickable').css('display', 'none');
        $('.left-side li a.act').removeClass('act');
        $('li#item-select-' + id + ' a').addClass('act');
        $('#item-' + id).fadeIn('slow');
        $('#item-' + id).css('display', 'block');
    }
}

function changeTipsItem(id) {
    var curr = $("li[id^='tips-select-'] a.act").parent().attr('id').split('-')[2];
    if (curr != id) {
        $('#tips-box-' + curr).fadeOut('slow');
        $('#tips-box-' + curr).css('display', 'none');
        $('.pagination-tiny li a.act').removeClass('act');
        $('li#tips-select-' + id + ' a').addClass('act');
        $('#tips-box-' + id).fadeIn('slow');
    }
}
function switchProductTab(tab) {
    if (tab == 'comm') {
        $('li#tab-1 a').removeClass('act');
        $('li#tab-2 a').addClass('act');
        $('#comments-block').fadeIn('fast');
        $('#description-block').hide();
        $('.few-comments').hide();
        $('.comments-block-all .comments-list>div').show();
        $('.comments-block-all .tiny-filter').show();
        var comments_all = $('.comments-block-all .comments-list>div');
        var comment_all_holder = $('.comments-block-all .comments-list');
        $('.comments-block-all .all-comments').parent().show();

        if (comments_all.length > 25) {
            $('.comments-block-all .comments-list>div:gt(25)').hide();
            $('.tiny-filter').hide();
            $('.comments-block-all .all-comments').live('click', function() {
                comments_all.slideDown('slow');
                $('.tiny-filter').show();
                $('.comments-block-all .all-comments').parent().hide();
            });
        } else {
            $('.comments-block-all .all-comments').hide();
        }
    } else if (tab == 'desc') {
        $('li#tab-2 a').removeClass('act');
        $('li#tab-1 a').addClass('act');
        $('#description-block').fadeIn('fast');
        $('#comments-block').hide();
        $('.few-comments').show();
    }
}

function sortByDateAsc(a, b){
    var id_1 = parseInt(a.id.toString().split('-')[2]);
    var id_2 = parseInt(b.id.toString().split('-')[2]);
    return id_1 > id_2 ? 1 : -1;
};

function sortByDateDesc(a, b){
    var id_1 = parseInt(a.id.toString().split('-')[2]);
    var id_2 = parseInt(b.id.toString().split('-')[2]);
    return id_1 < id_2 ? 1 : -1;
};

function sortComments(type) {
    var sorted;
    if (type == 'asc') {
        $('.comments-block-all a.fr.block.tiny-filter').attr('onclick', '').unbind().click(function() { sortComments('desc'); return false; });
        $('.comments-block-all a.fr.block.tiny-filter').html('Seniausi');
        sorted = $(".comments-block-all div[id^='comment-id']").sort(sortByDateAsc);
        delete sorted;
    } else if (type == 'desc') {
        $('.comments-block-all a.fr.block.tiny-filter').attr('onclick', '').unbind().click(function() { sortComments('asc'); return false; });
        $('.comments-block-all a.fr.block.tiny-filter').html('Naujausi');
        sorted = $(".comments-block-all div[id^='comment-id']").sort(sortByDateDesc);
        delete sorted;
    }
    $(".comments-block-all div[id^='comment-id']").remove();
    $(".comments-block-all .comments-list").append(sorted);
    return false;
}

/*
function hideSubmenu() {
    $('.subnav').css('display', 'none');
}
*/

function productAddToCart(id) {
  $.ajax({
            type: "GET",
            url: "/cart/add/" + id + "/" + $('#product-info').val(),
            dataType: "json"
        });
    if ($('#warranty').len && $('#warranty').val() != '-') {
      $.ajax({
                type: "POST",
                url: "/cart/add_warranty/" + id + "/" + $('#warranty').val(),
                dataType: "json"
            });
    }
    $popup = $('#product_added');
    popup_block($popup);
    $('#product_added').show();
    return false;
}

function warrantyAddToCart(id, months) {
  $.ajax({
            type: "GET",
            url: "/cart/add_warranty/" + id + "/" + months,
            dataType: "json"
        });
    
    $popup = $('#warranty_added');
    popup_block($popup);
    $('#warranty_added').show();
    return false;
}

var popupStatus = 0;
function popup_block($popup)
{
    var windowWidth = document.documentElement.clientWidth;
    var windowHeight = document.documentElement.clientHeight;
    var popupHeight = $popup.height();
    var popupWidth = $popup.width();
        $popup.css({
            "position": "absolute",
            "top": windowHeight/2-popupHeight/2,
            "left": windowWidth/2-popupWidth/2
        });

    if(popupStatus==0){
        $("#backgroundPopup").fadeIn("slow");
        $("#backgroundPopup").css('opacity', 1.0);
        $popup.fadeIn("slow");
        popupStatus = 1;
    }

}

function popup_close($popup){
    if(popupStatus==1){
        $("#backgroundPopup").fadeOut("slow");
        $popup.fadeOut("slow");
        popupStatus = 0;
    }
}


function changeTopOffers() {
    if($(".list-6 a.act").length) {
        var active = $(".list-6 a.act").parent().attr('id').split('-')[2];
        var count = $(".list-6 a").size();
        var next = (active == count) ? 1 : (parseInt(active)+1);
        changeClickableItem(next);
    }
}

$(document).ready(function(){
    jQuery.fn.sort = function() {
       return this.pushStack([].sort.apply(this, arguments), []);
    };

    $('.few-comments .comments-list>div:gt(2)[id^="comment"]').hide();
    $('.few-comments .comments-list>div:last').show();

    var comments = $('#comments-block .comments-list>div');
    var comment_holder = $('#comments-block .comments-list');

    if (comments.length > 3) {
        $('#comments-block .comments-list>div:gt(2)').hide();
        $('.tiny-filter').hide();
        comment_holder.parent().append('<div class="fr">' +
                                            '<a style="margin-right: 10px;" class="fr block green-button all-comments">Rodyti Visus</a>' +
                                        '</div>' +
                                        '<div class="clr">&nbsp;</div>'
                                       );
        $('#comments-block .all-comments').live('click', function() {
            $('.comments-block-all .all-comments').show();
            switchProductTab('comm');
            //comments.slideDown('slow');
            //$('.tiny-filter').show();
            //$('#comments-block .all-comments').parent().hide();
        });

    }

    $('.few-comments .all-comments').live('click', function() {
        $('#comments-block .comments-list>div').show();
        $('#tiny-filter').show();
        $('#comments-block .all-comments').parent().hide();
        switchProductTab('comm');
    });

    $('.post-comment').live('click', function() {
        $('.comment-form').fadeIn('slow');
    });

    $('.few-comments .post-comment').live('click', function() {
        switchProductTab('comm');
        $('.few-comments').hide();
        $('.comment-form').show();
    });

    if (comments.length == 0) {
        $('.comment-form').show();
    }
    
    $('#super-menu li').hover(
        function() {
            $id = $(this).attr('id').split('-')[1];
            $('#sub-nav-'+$id).show();
            $('li #' + $id).addClass('act');
        },
        function () {
            $id = $(this).attr('id').split('-')[1];
            $('#sub-nav-'+$id).hide();
        }
    );
    $('.subnav').hover(
        function() {
            $(this).show();
        },
        function() {
            $(this).hide();
        }
    );

    $('div .delivery .city .title').live('click', function() {
            if ($(this).parent().find('.address_info:visible').length == 0) {
                $(this).parent().find('.address_info').css('border-bottom', '1px solid #DCE5A7');
                $(this).parent().find('.address_info:last').css('border-bottom', 'none');
                $('div .delivery .city').find('.title').css('border-bottom', 'none');
                $('div .delivery .city').find('.address_info:visible').slideUp();
                $(this).parent().find('.address_info').slideDown();
                $(this).parent().find('.title').css('border-bottom', '1px solid #DCE5A7');
                var coord = $(this).parent().find('.coord').val();
                if (coord) {
                   	if (GBrowserIsCompatible()) {
		                map = new GMap2($(this).parent().find('.map')[0]);
		                map.setCenter(new GLatLng(coord.split(',')[0], coord.split(',')[1]), 15); 
		                map.addControl(new GSmallZoomControl());
		            }
		            var marker = new GMarker(new GLatLng(coord.split(',')[0], coord.split(',')[1]));
		            map.addOverlay(marker);
		        }
            } else {
                $(this).parent().find('.address_info').slideUp();
                $('div .delivery .city').find('.title').css('border-bottom', 'none');
            }
    });
    
    $(function() {
    	var active = $('div .delivery .city .title').parent().find('.address_info:visible');
    	var coord = active.parent().find('.coord').val();
        if (coord) {
           	if (GBrowserIsCompatible()) {
                map = new GMap2(active.parent().find('.map')[0]);
                map.setCenter(new GLatLng(coord.split(',')[0], coord.split(',')[1]), 15); 
                map.addControl(new GSmallZoomControl());
            }
            var marker = new GMarker(new GLatLng(coord.split(',')[0], coord.split(',')[1]));
            map.addOverlay(marker);
        }

    });

    $('.value').css('cursor', 'pointer');
    $('.value').click(function() {
	switchProductTab('comm');
        window.location.hash = '#komentarai';
    });
    $('.stars').css('cursor', 'pointer');
    $('.stars').click(function() {
        window.location = $('a', $(this).parent()).attr('href') + '#komentarai';
    });

    var myInterval = setInterval("changeTopOffers()", 30000);

    $('.clear_form').click(function() {
        $('#send_request')[0].reset();
    });

    if (window.location.toString().split("#")[1] == 'komentarai') {
        switchProductTab('comm');
    } else {
        switchProductTab('desc');
    };

    $(".editable").editable("/client/setup/", {
        'onblur': 'submit',
        submitdata : {'inline': '1'}
    });

    $('.address').click(function(){
        data = ''
        $.get("/client/setup/", { address_id: $(this).attr('id') },
            function(data){
                $('.address_form .title').html('Redaguoti');
                $('.address_form #address_id').attr('value', data[0]['pk']);
                $('.address_form #id_city').attr('value', data[0]['fields']['city']);
                $('.address_form #id_street').attr('value', data[0]['fields']['street']);
                $('.address_form #id_house').attr('value', data[0]['fields']['house']);
                $('.address_form #id_flat').attr('value', data[0]['fields']['flat']);
            }, "json");
        return false;
    });

    
    /*	
    hideSubmenu();

    $('#super-menu').bind("mouseout", close);
    $('#super-menu').bind("mouseover", function() { clearTimeout(hideTimer); });// stop drop down menu from being closed

    var hideTimer = setTimeout(function() {  }, 1);//initialise so not undefined

    function close() {
        clearTimeout(hideTimer);
        hideTimer = setTimeout(function() { $('.subnav').fadeOut('fast'); }, 80);//close drop down menu  
    };
    */

    /*
    var popupStatus = 0;
    function popup_block($popup)
    {
        var windowWidth = document.documentElement.clientWidth;
        var windowHeight = document.documentElement.clientHeight;
        var popupHeight = $popup.height();
        var popupWidth = $popup.width();
            $popup.css({
                "position": "absolute",
                "top": windowHeight/2-popupHeight/2,
                "left": windowWidth/2-popupWidth/2
            });

        if(popupStatus==0){
            $("#backgroundPopup").fadeIn("slow");
            $("#backgroundPopup").css('opacity', 1.0);
            $popup.fadeIn("slow");
            popupStatus = 1;
        }

    };
    */

    function popup_close($popup){
        if(popupStatus==1){
            $("#backgroundPopup").fadeOut("slow");
            $popup.fadeOut("slow");
            popupStatus = 0;
        }
    };

    $('.quantity').change(function () {
        $(this).parents('form').submit();
    });

    $('.delivery input').change(function () {
        $(this).parents('form').submit();
    });

    $('.thumb-list li').click(function(e){
        
        e.preventDefault();
        
        $(this).parents().find('li').removeClass('act');
        
        if ($(this).hasClass('youtube')) {
            $(this).parents('.item').find('table img').hide();
            $object = $(this).find('.select_video').clone();
            //console.log($object);
            if (!$(this).parents('.item').find('.tac object').size())
                $(this).parents('.item').find('.tac').append($object);
            $(this).parents('.item').find('table object').show().css("display", "inline");
        } else {
            $src = $(this).find('.select_image').attr('src');
            $(this).parents('.item').find('table object').remove();
            $(this).parents('.item').find('table img').show();
            $(this).parents('.item').find('table img').attr('src', $src);
        }
        
        $(this).addClass('act');
    });
    $('.form_login .popup_remind').click(function(){
        $popup = $('#popup_remind');
        popup_block($popup);
        $('#popup_remind').show();

        return false;
    });
    $('li .popup_login').click(function(){
        $popup = $('#popup_login');
        popup_block($popup);
        $('#popup_login').show();

        return false;
    });
    $('#offer_price a').click(function(){
        $popup = $('#popup_offer');
        popup_block($popup);
        $('#popup_offer').show();

        return false;
    });

    $('.offer-price .tac a').click(function() {
        $.ajax({
            type: "POST",
            url: "/product/" + $('#product-info').attr('name').split('_')[1] + "/offer" ,
            data: 'opt-1=' + $('#offer-opt-1').val() + '&opt-2=' + $('#offer-opt-2').val() + '&chk=' + $('#offer-chk').attr('checked')
        });
        popup_close($('.offer-price'));
    });
    /*
    $('li .product_added').click(function(){
        //$('body').animate({opacity:0.5},300);
        $popup = $('#product_added');
        popup_block($popup);
        $('#product_added').show();

        return false;
    });
    */

    $('.popup-1 .close').click(function(){
        //$('body').animate({opacity:1},300);
        $(this).parents('.popup-1').hide();
        popup_close($(this).parents('.popup-1'));
    });

    $('.submit').click(function() {
        $(this).parents('form').submit();
    });
    $('.discount').click(function () {
        $(this).parents('form').submit();
        return false;
    });

    $('.star').click(function() {
        $(this).parents('.your-value').find('.fr').html("Įvertinote");
    });

    $('.title-slider li').click(function() {
        clearTimeout(myInterval);
        id = $(this).attr('id').split('-')[2];
        changeClickableItem(id);
    });

        
    if (screen.width>=1280) {
        $.cookie("big_screen", 'True', { expires: 30 });
    }
    else {
        $.cookie("big_screen", 'False', { expires: 30 });
    }
});
