function getCookie(name) {
    var cookieValue = null;
    if (document.cookie && document.cookie != '') {
        var cookies = document.cookie.split(';');
        for (var i = 0; i < cookies.length; i++) {
            var cookie = jQuery.trim(cookies[i]);
            // Does this cookie string begin with the name we want?
            if (cookie.substring(0, name.length + 1) == (name + '=')) {
                cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                break;
            }
        }
    }
    return cookieValue;
}
function deserialize(str) {
    var href = str,
        last_index = href.lastIndexOf("?"),
        result = {};
    if (last_index > -1) {
        href = href.substr(last_index + 1);
    }
    var data = href.split("&")
    for (var i = 0; i < data.length; i++) {
        if (!data[i]) continue;
        var pair = decodeURIComponent(data[i]).split("=");
        if (pair.length != 2) continue;
        var _name = pair[0];
        var value = pair[1];
        result[_name] = value;
    }
    return result;
}
$.ajaxSetup({
    cache: false,
    type: 'POST',
    dataType: 'html',
    beforeSend: function(xhr, settings) {
        if (!(/^http:.*/.test(settings.url) || /^https:.*/.test(settings.url))) {
            xhr.setRequestHeader("X-CSRFToken", getCookie('csrftoken'));
        }
    }
});
$(document).ready(function() {
    $("#RotatorWraper").rotator({
        'items': '.RotatorItem',
        'prev': '#LeftRotatorArrow',
        'next': '#RightRotatorArrow',
        'visibleCount': 1,
        'changeCount' : 1
		/*'useSwipeTouch': true,*/
    });
    $("#GallerySlideShow").rotator({
        'items': '.GalleryItem',
        'prev': '#PrevGalleryArrow',
        'next': '#NextGalleryArrow',
        'visibleCount': 1,
        'changeCount' : 1
    });
    
    /*Прелоад картинок*/
    var loaded_urls = new Array();
    $("div[bgimage]").each(function(){
        var current_object = $(this),
            bgimage = current_object.attr('bgimage');
        current_object.prepend('<div class="PreLoader"><img src="/media/Images/loader.gif"/></div>');
        if ($.inArray(bgimage, loaded_urls) == -1) {
            loaded_urls.push(bgimage);
            $("<img />")
                .attr('src', bgimage)
                .load(function(response){
                    var img = $(response.currentTarget).attr('src');
                    var obj = $("div[bgimage='"+img+"']").css("background", "url('"+img+"')");
                    obj.children('.PreLoader').remove();
                });
        }
    });
    /*$("img[preload]").each(function(){
        var current_object = $(this),
            image = current_object.attr('src');
        current_object.prepend('<div class="PreLoader"><img src="/media/Images/loader.gif"/></div>');
        if ($.inArray(image, loaded_urls) == -1) {
            loaded_urls.push(image);
            $("<img />")
                .attr('src', image)
                .load(function(response){
                    var img = $(response.currentTarget).attr('src');
                    var obj = $("img[src='"+img+"']").attr("src", img);
                    obj.children('.PreLoader').remove();
                });
        }
    });*/
    
    /* Кнопка "Добавить в корзину" */
    $(".AddToCart[object_id]").live('click', function () {
		var obj = $(this);
		var product = parseInt($(this).attr("object_id"), 10);
		var data = { product: product };
        if (product) {
			obj.slideUp();
			$.ajax({
				url: '/cart/add/',
				data: data,
				dataType: 'html',
				success: function (data) {
					obj.slideDown();
                    if ($("#CartContainer").is(":visible")) {
                        $("#CartContainer").show()
                            .animate({"left": "+=35px"}, 500).delay(500)
                            .animate({"left": "-=35px"}, 250);
                    }
                    else {
                        var width = $("#CartContainer").outerWidth();
                        $("#CartContainer").css('left', "-="+width).show()
                            .animate({"left": "+="+(width+35)+"px"}, 500).delay(500)
                            .animate({"left": "-=35px"}, 250);
                    }
                }
			});
		}
		return false;
	});
    
    /* Дополнительная менюшка в панели коллекций */
    $("#CollectionOpenButton, #ContentNavItemOpenButton").click(function(){
        obj = false;
        if ($(this).attr("id") == 'CollectionOpenButton') obj = $("#CollectionOpenItems");
        if ($(this).attr("id") == 'ContentNavItemOpenButton') obj = $("#ContentNavItemOpenItems");
        if (!obj) return;
        if (obj.is(":visible")) obj.hide();
        else obj.show();
        return false;
    });
    
});
