$(function() {

	var is_toogled = false;
	$('body').prepend('<div id="overlay"></div>');

	$('#log_in').toggle(
		function() {
			is_toogled = true;
			var arrPageSizes = ___getPageSize();
			$('#overlay').css({opacity: 0.30, width: arrPageSizes[0], height: arrPageSizes[1] }).fadeIn();
			$('#authoriz, #close').show();
			$('#close').click(function() {
				$(this).hide();
				$('#authoriz').hide();
				_finish();
				if( is_toogled == true ) { $('#log_in').click(); }
				return false;
			});
			return false;
		},
		function() {
			$('#authoriz, #close').hide();
			is_toogled = false;
			_finish();
			return false;
		}
	);

	function _finish() {
		$('#overlay').fadeOut(function() { $('#overlay').hide(); });
		// Show some elements to avoid conflict with overlay in IE. These elements appear above the overlay.
		$('embed, object, select').css({ 'visibility' : 'visible' });
	}

	function ___getPageSize() {
		var xScroll, yScroll;
		if (window.innerHeight && window.scrollMaxY) {
			xScroll = window.innerWidth + window.scrollMaxX;
			yScroll = window.innerHeight + window.scrollMaxY;
		} else if (document.body.scrollHeight > document.body.offsetHeight){ // all but Explorer Mac
			xScroll = document.body.scrollWidth;
			yScroll = document.body.scrollHeight;
		} else { // Explorer Mac...would also work in Explorer 6 Strict, Mozilla and Safari
			xScroll = document.body.offsetWidth;
			yScroll = document.body.offsetHeight;
		}
		var windowWidth, windowHeight;
		if (self.innerHeight) {	// all except Explorer
			if(document.documentElement.clientWidth){
				windowWidth = document.documentElement.clientWidth;
			} else {
				windowWidth = self.innerWidth;
			}
			windowHeight = self.innerHeight;
		} else if (document.documentElement && document.documentElement.clientHeight) { // Explorer 6 Strict Mode
			windowWidth = document.documentElement.clientWidth;
			windowHeight = document.documentElement.clientHeight;
		} else if (document.body) { // other Explorers
			windowWidth = document.body.clientWidth;
			windowHeight = document.body.clientHeight;
		}
		// for small pages with total height less then height of the viewport
		if(yScroll < windowHeight){
			pageHeight = windowHeight;
		} else {
			pageHeight = yScroll;
		}
		// for small pages with total width less then width of the viewport
		if(xScroll < windowWidth){
			pageWidth = xScroll;
		} else {
			pageWidth = windowWidth;
		}
		arrayPageSize = new Array(pageWidth,pageHeight,windowWidth,windowHeight);
		return arrayPageSize;
	};

    $('#comments #hform-comment').keyup(function(){
        var length = jQuery.trim(this.value).length;
        $('#comment-length').css('color', ((length <= 1000 && length >= 10) ? '#555' : '#f55')).html('Введено знаков: ' + length + '/1000');
    });
    $('#comments #hform-submit').click(function(){
        var length = jQuery.trim($('#hform-comment').val()).length;
        if (length < 10){
            alert('Слишком короткий комментарий!');
            return false;
        }
        else if (length > 1000){
            alert('Слишком длинный комментарий!');
            return false;
        }
        return true;
    });
    
    $('#comments .comment-remove a').click(function(){
        if (confirm('Удалить комментарий?')){
            var comment = $(this.parentNode.parentNode);
            $.get(this.href, {ajax:1},
                function(data){
                    comment.fadeOut();
                }
            );
        }
        return false;
    });
    
    if ($('#topproducts .remove').length){
        $(function(){
            $('#topproducts').sortable({ opacity: 0.6, cursor: 'move', update: function(){ PopularProducts.order(); },
            stop: function(){ $('#topproducts>li').css({top: 'auto', left: 'auto'}); /** fix bug for Opera 9.24 */ }});
        });
    }

    if ($('#topbrands .remove').length){
        $(function(){
            $('#topbrands').sortable({ opacity: 0.6, cursor: 'move', update: function(){ PopularBrands.order(); },
            stop: function(){ $('#topproducts>li').css({top: 'auto', left: 'auto'}); /** fix bug for Opera 9.24 */ }});
        });
    }

});

var Search = {
    
    cache : {},
    
    create_radio_options : function (name){
        var out = '<label><input type="radio" value="null" name="' + name + '" ' + ((typeof(post[name]) == 'undefined' || post[name] === 'null') ? 'checked="checked"' : '') + ' /> <span>Все варианты</span></label>';
        out += '<label><input type="radio" value="1" name="' + name + '" ' + ((typeof(post[name]) != 'undefined' && parseInt(post[name]) === 1) ? 'checked="checked"' : '') + ' /> <span>Есть</span></label>';
        out += '<label><input type="radio" value="0" name="' + name + '" ' + ((typeof(post[name]) != 'undefined' && parseInt(post[name]) === 0) ? 'checked="checked"' : '') + ' /> <span>Нет</span></label>';
        return out;
    },
    
    create_select_options : function (name, options){
        var out = '<option value="null">Все варианты</option>';
        for (var i in options)
            out += '<option value="' + i + '"' + ((typeof(post[name])!='undefined' && post[name]==i)?' selected="selected"':'') + '>' + options[i] + '</option>';
        return out;
    },
    
    create_parameter : function(name, field){
        switch (field.type){
            case 'boolean':
                var node = $.create('div', {className : 'hform-radio-group'}, '').html('<span class="title">' + field.name + (field.postfix ? ', ' + field.postfix : '') + '</span>' + Search.create_radio_options(name));
                break;
            case 'list':
                var node = $.create('div', {className : 'hform-select'}, '').html('<span>' + field.name + (field.postfix ? ', ' + field.postfix : '') + '</span><select title="' + field.name + (field.postfix ? ', ' + field.postfix : '') + '" name="' + name + '">' + Search.create_select_options(name, field.options) + '</select>');
                break;
        }
        node.appendTo('#select-parameters');
    },

    show_parameters: function(json){
        if (json){
            var length = 0;
            for (field in json){
                length++;
                Search.create_parameter(field, json[field]);
            }
            if (length) $('#select-parameters').slideDown(700);
        }
    },
    
    preload : function(parent, json){
        if (parent){
            Search.cache[parent] = json;
            Search.show_parameters(json);
        }
    },
    
    parameters: function(select){
        if (!window.post) window.post = {};
        $('#select-parameters').slideUp().html('');
        if (parseInt(select.value)){ 
            if (typeof Search.cache[select.value] == 'undefined'){
                $('#select-status').show();
                $.getJSON(SITE_URL + 'search/', {parameters : 'true', ajax : 'true', parent : select.value}, function(json){
                    $('#select-status').fadeOut('loading');
                    Search.cache[select.value] = json;
                    Search.show_parameters(json);
                    
                });
            }
            else Search.show_parameters(Search.cache[select.value]);
        }
    }
    
};

var PopularProducts = {
    
    add: function(element, id){
        if (element.className.indexOf('loading') + element.className.indexOf('ready') == -2){
            element.className = 'popularproducts-add-loading';
            $.get(SITE_URL + 'userspace.php?controller=shop&method=populars', {action : 'add', id : id}, function(data){
                element.className = 'popularproducts-add-ready';
                $(element).html('Добавлен');
            });
        }
    },
    
    remove: function(element){
        if (confirm('Удалить элемент из списка?')){
            var node = element.parentNode.parentNode.parentNode;
            $('#topproducts').addClass('loading');
            var id   = node.id.substr(8);
            $.get(SITE_URL + 'userspace.php?controller=shop&method=populars', {action : 'remove', id : id}, function(data){
                $('#topproducts').removeClass('loading');
                $(node).fadeOut();
            });
        }
    },
    
    order: function(){
        $('#topproducts').addClass('loading').sortable('disable');
        $.post(SITE_URL + 'userspace.php?controller=shop&method=populars&action=order', {order : $('#topproducts').sortable('toArray').join(',').replace(/product_/g, '')}, function(data){
            $('#topproducts').removeClass('loading').sortable('enable');
            /** fix bug for MSIE */
            if ($.browser.msie) $('#topproducts>li').css('opacity', 'auto');
        });
    }
    
};

var PopularBrands = {
    
    status: 0,
    
    element: false,
    
    images: [],
    
    add: function(element, category_id, brand_id){
        if (element.className.indexOf('loading') + element.className.indexOf('ready') == -2){
            element.className = 'popularbrands-add-loading';
            $.get(SITE_URL + 'userspace.php?controller=shop&method=brands', {action : 'add', category_id : category_id, brand_id : brand_id}, function(data){
                element.className = 'popularbrands-add-ready';
                $(element).html('Добавлен');
            });
        }
    },
    
    select: function(){
        if (PopularBrands.status){
            var img = $('#selectbrands').val();
            $('#selectbrands').hide();
            PopularBrands.status = -1;
             $('#topbrands').addClass('loading');
            $.post(SITE_URL + 'userspace.php?controller=shop&method=brands&action=edit', {id: PopularBrands.element.parentNode.parentNode.parentNode.id.substr(9), image: img}, function(data){
                $('#topbrands').removeClass('loading');
                $('img', PopularBrands.element.parentNode.parentNode.parentNode).get(0).src = SITE_URL + 'uploads/brands/' + img;
            });
        }
        PopularBrands.status++;
    },
    
    showSelect: function(){
        PopularBrands.status = 0;
        if (PopularBrands.element){
            var id  = PopularBrands.element.parentNode.parentNode.parentNode.id.substr(9);
            var pos = $(PopularBrands.element).position();
            if ($.browser.msie && $.browser.version < 7) pos.left -= 120;
            else pos.top += 160;
            $('#selectbrands').css(pos).show();
        }
    },
    
    edit: function(element){
        PopularBrands.element = element;
        if (!$('#selectbrands').length){            
            $('#topbrands').addClass('loading');
            $.getJSON(SITE_URL + 'userspace.php?controller=shop&method=brands', {action : 'images'}, function(data){
                if (data){
                    var select = '<select id="selectbrands" onclick="PopularBrands.select();">';
                    for (var i = 0; i < data.length; i++) select += '<option name="' + data[i] + '">' + data[i] + '</option>';
                    $('body').append(select + '</select>');
                    $('#topbrands').removeClass('loading');
                    PopularBrands.showSelect();
                }
            });
        }
        else PopularBrands.showSelect();
    },
    
    remove: function(element){
        if (confirm('Удалить элемент из списка?')){
            var node = element.parentNode.parentNode.parentNode;
            $('#topbrands').addClass('loading');
            var id   = node.id.substr(9);
            $.get(SITE_URL + 'userspace.php?controller=shop&method=brands', {action : 'remove', id : id}, function(data){
                $('#topbrands').removeClass('loading');
                $(node).fadeOut();
            });
        }
    },
    
    order: function(){
        $('#topbrands').addClass('loading').sortable('disable');
        $.post(SITE_URL + 'userspace.php?controller=shop&method=brands&action=order', {order : $('#topbrands').sortable('toArray').join(',').replace(/topbrand_/g, '')}, function(data){
            $('#topbrands').removeClass('loading').sortable('enable');
            /** fix bug for MSIE */
            if ($.browser.msie) $('#topbrands>li').css('opacity', 'auto');
        });
    },
    
    help: function(){
        alert('Для того, чтобы загрузить новые логотипы. Войдите в "Мой раздел > Допольнительные инструменты > Управление файлами" и загрузите изображения в папку "brands".');
    }
    
};
