function setCookie (name, value, expires, path, domain) {
    var S = name + "=" + escape(value) +
                      ((expires) ? "; expires=" + expires : "") +
                      ((path) ? "; path=" + path : "") +
                      ((domain) ? "; domain=" + domain : "");
    document.cookie = S;

}

function getCookie (name) {
    var cookie = " " + document.cookie;
    var search = " " + name + "=";

    var offset = cookie.indexOf (search);
    var end = 0;
    if (offset != -1) {
        offset += search.length;
        end = cookie.indexOf(";", offset)
        if (end == -1) {
            end = cookie.length;
        }
        return unescape (cookie.substring(offset, end));
    }
    return false; // return ''
}

function setCookieHidden(name) {
    var hidden = getCookie('hidden');

    if (hidden) {
        if (hidden.indexOf(name) == -1) {
            setCookie('hidden', hidden + "|" + name, new Date('Mon, 01-Jan-2020 00:00:00 GMT'), '/');
        }
    } else {
        setCookie('hidden', "|" + name, new Date('Mon, 01-Jan-2020 00:00:00 GMT'), '/');
    }
}

function setCookieVisible(name) {
    var hidden = getCookie('hidden');
    if (hidden) {
        setCookie('hidden', hidden.replace("|"+name, ''), new Date('Mon, 01-Jan-2020 00:00:00 GMT'), '/');
    }
}

function toggleCommentForm (itemId, db, docId, commentText) {
    return $('#comments_form_' + itemId).length ? $('#comments_form_' + itemId).remove() : renderCommentForm (itemId, db, docId, commentText);
}

function renderCommentForm (itemId, db, docId, commentText) {
	$('#r' + itemId).after(
		'<tr id="comments_form_' + itemId + '">' +
			'<td class="comment" colspan="3">' +
				'<form onsubmit="return saveComment(\'' + itemId + '\', \'' + db + '\', \'' + docId + '\')">' +
					'<input type="hidden" name="db" value="' + db + '" />' +
					'<input type="hidden" name="id" value="' + docId + '" />' +
					'<p>Введите текст комментария:</p>' +
					'<div class="c-input">' +
						'<input type="submit" class="c-button" value="Ок" />' +
						'<input type="text" name="comment" class="text c-text">' +
					'</div>' +
				'</form>' +
			'</td>' + 
		'</tr>'
	);
	return false;
}

function saveComment(itemId, db, docId) {
	var comment = $('#comments_form_' + itemId + ' input[name=comment]').attr('value');
    prependSavedObj(itemId, comment, db);
	if (comment.length) {
		$('#r' + itemId ).find('.bhvr-commentcontainer').show().find('SPAN').text(comment);
		$('#r' + itemId ).find('.bhvr-favcontrol A:last').text('изменить комментарий');
	} else {
		$('#r' + itemId ).find('.bhvr-commentcontainer').hide();
		$('#r' + itemId ).find('.bhvr-favcontrol A:last').text('оставить комментарий');
	}
	
	$.post('/a_saveComment.shtml', $('#comments_form_' + itemId + ' FORM').serialize());
	$('#comments_form_' + itemId).remove();
	return false;
}

function prependSavedObj(itemId, comment, db) {
    var vac_title = $( $('#r' + itemId ).find('a').get(0) ).text();
    var vac_href  = $( $('#r' + itemId ).find('a').get(0) ).attr('href');
    var vac_info  = '';
	var props_selectors = (db == 'vac') ? ['.company', '.doc-city', '.gross'] : ['.doc-city', '.gross'];
	for (var i = 0; i < props_selectors.length; i++) {
		var prop_value = $('#r' + itemId).find(props_selectors[i]).text();
		if (prop_value) {
			if (vac_info) {
				vac_info += ', ';
			}
			vac_info += prop_value;
		}
	}
	vac_info = '<span class="saved_props">' + $('<span/>').text(vac_info).html() + '</span>';
	
    var additional = '' ;
    if ( comment.length ) {
        additional = '<br />' + '<span class="saved_comment">' + $('<span/>').text(comment).html() + '</span>';
    }
    if ( $('#favorite_' + itemId ).length ) {
         $('#favorite_' + itemId ).remove();
    }

    var object = "<li id='favorite_" + itemId +  "'><a href='" + vac_href + "'>" + vac_title + "</a>" + '<br />' + vac_info + additional + "</li>";
    $('#saved_stuff').prev().show();
    $('#saved_stuff').show().find('.bhvr-clear').parent().show();
    $('#saved_stuff').prepend(object);
}

function saveDocument (itemId, db, docId) {
    prependSavedObj(itemId, '', db);
	$.get('/a_saveComment.shtml', {id: docId, db: db});
    
    $('#r' + itemId).find('.bhvr-favadd').hide();
    $('#r' + itemId).find('.bhvr-favcontrol').show();
    return false;
}

function showSavedObjects() {
	$('#show_saved_objects_link').hide();
    $('#saved_stuff LI').show();
}

function showhideCookizedBlock (idPfx) {
    var sCook = getCookie ('hidden');
    if (sCook && sCook.indexOf(idPfx) != -1) {
        $('#' + idPfx).parent().removeClass('open').addClass('close').next().hide();
    }
}

$(document).ready(function(){
    $('.bhvr-show-filters').click(function(e){
        e.preventDefault();
        $(this).parent().siblings().show();
        $(this).parent().remove();
    });
    
    $('.bhvr-show-hide-block').click(function(e){
        e.preventDefault();
        $(this).parent().next().toggle();
        if ($(this).parent().toggleClass('open').toggleClass('close').hasClass('open')) {
            setCookieVisible($(this).attr('id'));
        } else {
            setCookieHidden($(this).attr('id'));
        }
    });
    
    $('.bhvr-show-hide-category').click(function(e){
        e.preventDefault();
        $(this).parent().toggleClass('li-open');
        $(this).next().toggle();
    });
    
    $('.bhvr-clear').click(function(e){
        e.preventDefault();
        rule = eval( "(" + $(this).attr('rel') + ")" );
        $.get('/a_cleanBlock.shtml', rule);
        $(this).parent().prevAll().remove();
        $(this).parent().parent().hide().prev().hide();
        $(this).parent().hide();
    });
    
    $('.bhvr-unfav-all').click(function(e){
        e.preventDefault();
		$('.bhvr-commentcontainer').hide();
        $('.bhvr-favcontrol A:last').text('оставить комментарий');
        $('.bhvr-favcontrol').hide();
        $('.bhvr-favadd').show();
    });
	
	$(document.body).click(function(){
		$('#selectContainer').hide();
	});
	
	$('#selectCurrent').click(function(){
		$('#selectContainer').toggle();
		return false;
	});
	
	$('#selectContainer A').click(function() {
		$('#selectCurrent DIV').text($(this).text());
		$('#selectContainer').hide();
		if ($(this).attr('rel').length) {
			if (!$('#searchform INPUT[name=rparent]').length) {
				$('#searchform').append('<input type="hidden" name="rparent" value="" />');
			}
			$('#searchform INPUT[name=rparent]').attr('value', $(this).attr('rel'));
		} else {
			$('#searchform INPUT[name=rparent]').remove();
		}
		return false;
	});
	
	$('#searchform').unbind().submit(function() {
		$('#words.inactive').attr('value', '');
		var rparent = $('#searchform INPUT[name=rparent]').attr('value') || '';
		var old_rparent = $('#selectContainer').attr('rel') || '';
		if (rparent != old_rparent) {
			$('#searchform INPUT[name=tags]').attr('value', '');
		}
	});
	
	if ($('#words').attr('value') == 'Ключевые слова' || $('#words').attr('value') == '') {
		$('#words').attr('value', 'Ключевые слова').addClass('inactive');
	}
	
	$('#words')
		.focus(function(){
			if ($(this).is('.inactive')) {
				$(this).attr('value', '').removeClass('inactive');
			}
		})
		.blur(function(){
			if ($(this).attr('value') == '') {
				$(this).attr('value', 'Ключевые слова').addClass('inactive');
			}
		});
});
